I can work with basic generic expression but the wildcard-constraints just mess with my mind.
Info: Student extends Person and Person extends Animal
List<? super Animal> aList= new ArrayList<>();
// does not compile as expected,
// since the list is restricted to something that has Animal as superclass.
// aList.add(new Object());
aList.add(new Animal()); // I can add animal
aList.add(new Person()); // I can add Person
aList.add(new Student()); // I can add Student
Animal a = new Animal();
Animal b = new Animal();
Person p = new Person();
Student s = new Student();
// test
a = b; //I can assign an animal to another animal
a = p; // I can assign a person to an animal
a = s; // I can assign a student to an animal
Animal animal = aList.get(0); // DOES NOT COMPILE, WHY ?
QUESTION: I don't understand why the last assignment does not work. The examples above show, that anything in that list is definitely an animal, yet I can't get an animal from that list.
MORE SPECIFIC: When I know that I can add only types which have Animal as superclass, why can't I expect to remove objects from type Animal ?
FACT: I can ONLY add objects which extend Animal! I just tried to add a car object and it does not work !
I am starting to doubt my sanity, I hope you can help me. Thank You
Additionally:
Object animal = aList.get(0); // works
Why does this statement work even though I know that I can't add an Object-Type ?
SOLUTION: (Based on the accepted answer)
I misunderstood the meaning of <? super Animal>
What I thought it means: Any class which has Animal as superclass.
What it (apparently) means: Any Class which is superclass of Animal.
Therefore a List might also contain objects of type Object which is why Animal animal = aList.get(0);
fails.
Cheers