My hacking journal

Generics demistified

· by admin · Read in about 1 min · (172 Words)
generics java jls

Take this load of questions:

  • Why can I put an Integer in a List<Number> but can’t assign a List<Integer> to a List<Number>?
  • Why can I put any Number in a List<? super Number> but can’t do the same with a List<? extends Number>?
  • Why doesn’t List<? extends Number> extends List<? 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: