Re: Java Generics question
"Nicklas" <nicklas.lundgren@malmo.com> wrote in message
news:1160568089.922735.73620@h48g2000cwc.googlegroups.com...
-------------------------- Code Example --------------------------
import java.util.*;
public class AnimalGenericTester {
public AnimalGenericTester() {
ArrayList<Animal> myList = new ArrayList<Animal>();
myList.add(new Dog());
myList.add(new Cat());
printAnimal(myList);
}
void printAnimal(ArrayList<? super Cat> list) {
//What is the purpose of this???
//The myList now contains a Dog and a Cat but Dog is NOT a super of
cat
//I really can't see the point of this generic functionality
}
Dog might not be a superclass of cat, but Animal is, and if you pass
myList to that method, you're passing a List<Animal>, not a List<Dog>, so
everything checks out okay at compile time.
A List<? super Cat> doesn't mean that all the elements in the list are a
superclass of cat. It means that you've got a list of something (let's call
it A), and A is a superclass of Cat, and everything in that list is an
instance of A. In our specific case, A is Animal, but your printAnimal
method doesn't (need to) know that.
A List<? super Cat> is useful in that you know it is always safe to add
an instance of Cat to that list, because that list is a list of something
(again, let's call it A), and A is a superclass of Cat, so any Cat you add
is guaranteed to be an instance of A, and thus can be a member of that List.
- Oliver