What is a real life example of generic <? super T>

  • A+
Category:Languages

I understand that represents any super class of T (parent class of T of any level). But I really strugle to imagine any real life example for this generic bound wildcard.

Edit: I understand what means and I have seen this method:

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

What I am looking for is an example of real life use case where this construction can be used.

 


Suppose you have this class hierarchy: Cat inherits from Mammal, which in turn inherits from Animal.

List<Animal> animals = new ArrayList<>(); List<Mammal> mammals = new ArrayList<>(); List<Cat> cats = ... 

These calls are valid:

Collections.copy(animals, mammals); // all mammals are animals Collections.copy(mammals, cats);    // all cats are mammals Collections.copy(animals, cats);    // all cats are animals Collections.copy(cats, cats);       // all cats are cats  

But these calls are not valid:

Collections.copy(mammals, animals); // not all animals are mammals Collections.copy(cats, mammals);    // not all mammals are cats Collections.copy(cats, animals);    // mot all animals are cats 

So the method signature simply insures that you copy from a more specific (lower in the inheritance hierarchy) class to a more generic class (upper in the inheritance hierarchy), and not the other way round.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: