I'm trying to follow the oracle documentation for generics in collection, for upper bounds and lower bounds, but it is creating confusion.. as
import java.util.ArrayList;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
List<Dog> dogList = new ArrayList<>();
dogList.add(new Dog());
dogList.add(new Dog());
List<Cat> catList = new ArrayList<>();
catList.add(new Cat());
catList.add(new Cat());
List<Entity> entList = new ArrayList<>();
entList.add(new Entity());
entList.add(new Entity());
print(dogList);
print(catList);
print1(entList);
}
public static void print(List<? extends Animal> animals){
for(Animal an : animals){
System.out.println(an);
}
}
public static void print1(List<? super Animal> animals){
animals.add(new Animal());
animals.add(new Dog());
for(Object an : animals){
System.out.println(an);
}
}
}
class Entity {}
class Animal extends Entity{}
class Dog extends Animal {}
class Cat extends Animal {}
Now the confusion is , even the variable is of type List<? super Animal>
, i'm allowed to add new instances of dog, like, animals.add(new Dog())
... why???
also, if my variable is of type List<? extends Animal>
, it do not allow me to add instances of Animal, or Dog or Entity... any reasons ??