Generics demistified
Take this load of questions:
- Why can I put an
Integer
in aList<Number>
but can’t assign aList<Integer>
to aList<Number>
? - Why can I put any
Number
in aList<? super Number>
but can’t do the same with aList<? extends Number>
? - Why doesn’t
List<? extends Number>
extendsList<? super Number>
?
These and similar questions are asked very often, but usually answered like this:
Consider what happens with arrays:String[] strings = { "Foo", "Bar", "Baz" }; Object[] objects = strings; objects[0] = new Integer(1); // BOOOOM!
This kind of answer is misleading at best, because it pretends that generic types are a feature of the Collections framework of the platform, which is simply not true. Generics are a feature of Java-the-language, and are employed throughout the API (Class, Enum, Comparable) as well as in third party libraries (especially ones dealing with I/O, and thus reflection, like Jackson, jOOQ, etc.)
Relevant links: