Small Generics Examples



List<Number> nums = new ArrayList<Number>(); //ok

List<? super Number> sink = nums; //ok
//assignment is allowed. you can add element in sink list.

List<? extends Number> source = nums; // ok
//assignment is allowed. But you cannot add element in source list.

List<List<?>> lists = new ArrayList<List<?>>(); // ok

List<?> lists = new ArrayList<?>(); // COMPILE-TIME-ERROR
// You could not add element in the created list

Map<String, ? extends Number> map = new HashMap<String, ? extends Number>(); 
// compile-time error
// You could not add element in the created map

public void <T> check(List<? extends T> list){
list.add("1");// COMPILE-TIME-ERROR
// you cannot add element in list as it uses extends
}

public class Maths {
    public static <T> T findMax(T x, T y) {
        return x > y ? x : y; // COMPILE-TIME ERROR
// identify it by own
    }
}

//OK. you can take numbers from list 
public static void printNums(List<? extends Number> list) {
    for (Number n : list)
        System.out.print(n + " ");
    System.out.println();
}