What is the difference between 'super' and 'extends' in Java Generics [duplicate]
Solution 1:
It depends which way on the inheritance hierarchy it allows. Assume you have a class "Child" which inherits from "Parent" which inherits from "Grandparent".
<T extends Parent>
accepts either Parent or Child while <T super Parent>
accepts either Parent or Grandparent.
Solution 2:
There are three types of wildcards:
-
? extends Type
: Denotes a family of subtypes of typeType
. This is the most useful wildcard. -
? super Type
: Denotes a family of supertypes of typeType
. -
?
: Denotes the set of all types or any.
Solution 3:
See Effective Java 2nd Edition, Item 28:
PECS
Producer extends, Consumer super
If your parameter is a producer, it should be <? extends T>
, if it's a consumer it has to be <? super T>
.
Take a look at the Google Collections, they know how to use it, because they got Bloch ;)