I’m not sure why the last statement in the following code is illegal. Integer should be a subtype of ?, so why can’t I assign it to b?
List<String> a = new ArrayList<String>();
a.add("foo");
// b is a List of anything
List<?> b = a;
// retrieve the first element
Object c = b.get(0);
// This is legal, because we can guarantee
// that the return type "?" is a subtype of Object
// Add an Integer to b.
b.add(new Integer (1));
The point is that
brefers to a list of some type, but the compiler doesn’t know what the type is, so it doesn’t know whether or not it’s valid to add anIntegerto it. And a good thing too, given your example – you’d be adding anIntegerto an object initially created to hold a list of strings. Sure, that information is lost at execution time in Java – but the compiler tries to keep you as safe as it can.See the Java generics FAQ for a lot more information.