ArrayList<Integer> a = new ArrayList<Number>();
Does not work because the fact that Number is a super class of Integer does not mean that List<Number>
is a super class of List<Integer>
. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.
ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);
I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object>
is mostly used for return values of methods. Even in this example Object o = a1.get(0)
is valid.
ArrayList<?> a = new ArrayList<?>()
This does not work because you cannot instantiate list of unknown type...