Originally posted by Paul Kemp:
....
But the compiler is OK with this:
Why does the compiler accept this notation? Could this List ever been anything other than type Horse? If the object type must be specified, surely the List type has to be the same?
The above code is saying that you can take any type which is Horse and any SUPERCLASS. So Horse, Animal and Object can be accepted.
List<? super Horse> myList = new ArrayList<Horse>();
The above code is saying that you can take any type which is Horse and any SUPERCLASS. So Horse, Animal and Object can be accepted.
List<? super Horse> myList = new ArrayList<Horse>();
List<? super Horse> myList = new ArrayList<Animal>();
List<? super Horse> myList = new ArrayList<Object>();
List<? super Horse> myList = new ArrayList<WhiteHorse>();//wrong
List<? super Horse> myList = new ArrayList<Dog>();
SCJP 6
If you had said something like:
List<? extends Horse> myList = new ArrayList<Horse>();
Then this means any Horse or subclass of Horse is accepted.
SCJA
~Currently preparing for SCJP6
public void addAnimal(List<? super Dog> animals) {
animals.add(new Dog()); // adding is sometimes OK with super
}
public static void main(String[] args) {
List<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog());
animals.add(new Dog());
AnimalDoctorGeneric doc = new AnimalDoctorGeneric();
doc.addAnimal(animals); // passing an Animal List
}
public void addAnimal(List<Animal> animals) {
animals.add(new Dog()); // adding is sometimes OK with super
}
and call it:
addAnimal(new ArrayList<Cat> ) ;
animals.add(new Dog());
SCJP 6
Are these bits of code actually the same? They both allow polymorphism on subclasses of Horse...
List<Horse> myList = new ArrayList<Horse>();
myList.add(new ShireHorse());
List<? super Horse>myList2 = new ArrayList<Horse>();
myList2.add(new ShireHorse());
So one final question on this if I may...
List<? super ShireHorse>myList2 = new ArrayList<Animal>();
myList2.add(new ShireHorse());
The code above works OK. In fact, I can replace new ArrayList<Animal>(); with new ArrayList<Object>; new ArrayList<Horse>; and they all compile, so what is the significance of my choice of object on the right-hand side of the equals...?
Especially if List<? super ShireHorse>myList2 returns Objects anyway....
Why would you purposely use wildcards, when you know exactly what the collection is?
Why does the compiler accept this notation? Could this List ever be anything other than type Horse?
Originally posted by Paul Kemp:
Why does the compiler accept this notation at all? Why doesn't it just say, come on, you know what the collection type is, you just told me?
SCJP 6
Don't get me started about those stupid light bulbs. |