3

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 ??

sunilp
  • 51
  • 1
  • 4

1 Answers1

0

List<? super Animal> is a list of Animals or Entities or any Objects so you are allow to add a Dog to it. Dog is both Animal and Entity. That is

    List<Object> objList = new ArrayList<>();
    objList.add(new Dog());
    objList.add(new Animal());
    objList.add(new Entity());
    objList.add(new Object());
    print1(objList);

would compile without error or warning

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • agreed, but why then `List extends Animal>` is not allowed to add any Dog or Cat, as Dog extends Animal? – sunilp Jan 09 '14 at 06:24
  • List extends Animal> list means it may be a list of Dogs or Cats anysubclass , can you add Dog to list - no it may be list of Cats, Cat? not ... – Evgeniy Dorofeev Jan 09 '14 at 06:48