shyam patil shyam patil - 1 year ago 100
Java Question

Confusing Sentence In Generics And Collection Java

I am reading a book: Java Generics and Collections by maurice and philip.

There is one sentence which i think is wrong:
They have given a code:

public static <T> void copy(List<? super T> dst, List<? extends T> src) {
for (int i = 0; i < src.size(); i++) {
dst.set(i, src.get(i));

and the sentence is:

The quizzical phrase ? super T means that the destination list may
have elements of any type that is a supertype of T, just as the source
list may have elements of any type that is a subtype of T.

AFAIK, the
? super T
means destination list can have elements which are T and its SubType.
I have tested this here:

List<? super Dog> tList = new ArrayList<>();
tList.add(new Dog());
tList.add(new HotDog());

tList.add(new Animal());
is not allowed.
note that
HotDog extends Dog
Dog extends Animal

So if we go according to the book statement, which says tList(Destination list), being
? Super Dog(? super T)
, can have Animal's instance as it is the Super Type of Dog(T)

Answer Source

The quoted explanation is all wrong. List<? super T> is not a list that "may have elements of any type that is a supertype of T" because that would mean it's just a List<Object>.

The notation List<? super Dog> in fact does not describe one particular list type; it is better understood as a pattern against which specific list types are matched. List<Dog> and List<Animal> match this pattern, but List<HotDog> does not.

Now, if you review the above, you'll see that you can safely add instances of Dog or any of its subtypes to any list that satisfies the given pattern; in fact, the pattern exactly covers all list types where this is safe. This is why we use the <? super T> wildcard to generally describe a list that will accept data of type T (it will play the role of a consumer of T).

The opposite case, that of <? extends Dog>, describes all list types that can serve as producers of objects that satisfy instanceof Dog.

All of the above rules are succintly summarized in the PECS principle: "Producer extends, consumer super."

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download