Java generics super keyword

The bounded wildcard in List<? super Number> can capture Number and any of its supertypes. Since Number extends Object implements Serializable, this means that the only types that are currently capture-convertible by List<? super Number> are:

  • List<Number>
  • List<Object>
  • List<Serializable>

Note that you can add(Integer.valueOf(0)) to any of the above types. however, you CAN’T add(new Object()) to a List<Number> or a List<Serializable>, since that violates the generic type safety rule.

Hence it is NOT true that you can add any supertype of Number to a List<? super Number>; that’s simply not how bounded wildcard and capture conversion work. You don’t declare a List<? super Number> because you may want to add an Object to it (you can’t!); you do because you want to add Number objects to it (i.e. it’s a “consumer” of Number), and simply a List<Number> is too restrictive.

References

See also

  • Effective Java 2nd Edition, Item 28: Use bounded wildcards to increase API flexibility
    • “PECS stands for producer-extends, consumer-super

Related questions

  • Too many to list, PECS, new Integer(0) vs valueOf, etc

Leave a Comment