Generics in Java

Generic Class

class Box<T> {
    private T value;

    void set(T value) {
        this.value = value;
    }

    T get() {
        return value;
    }
}

How to use

Box<String> b1 = new Box<>();
b1.set("Java");

Box<Integer> b2 = new Box<>();
b2.set(100);

Generic Method

class Printer {
    static <T> void print(T value) {
        System.out.println(value);
    }
}

How to use

Printer.print("Hello");
Printer.print(123);
Printer.print(3.14);

Bounded Generics

In the below example only Integer, Double, Float will be allowed and not the String

class Calculator<T extends Number> {
    double square(T num) {
        return num.doubleValue() * num.doubleValue();
    }
}

Wildcard Generics

public class Test {

	void printList(List<?> list) {
	    for (Object o : list) {
	        System.out.println(o);
	    }
	}
}