As we know we can not add any value except null to collection if we use ? extends syntax. What if we want to add value to the collection, then we have to use ? super syntax. The code looks like this.
also read:
List<? super Dog> list1 = new ArrayList<dog>();
before discussing why it is possible to add, using ? super syntax, let us see what can be assignable to list1 in above code.? super Dog means, the collection using this syntax can take either collection of same generic type or super generic type.
List<? super Dog> list1 = new ArrayList<dog>(); List<? super Dog> list2 = new ArrayList<animal>(); List<? super Dog> list3 = new ArrayList<object>();
above three line will compile but not below line
List<? super Animal> list4 = new ArrayList<dog>();
And now let us see what we can add to collection, if we use ? super syntax. we can add same generic type or sub type of the generic type used in the declaration.
so we can add Animal or Cat or Dog to below collection
List<? super Animal> list = new ArrayList<animal>();
Now the question is why we are allowed to add values to collection if we use ? super, which is not possible if we use ? extend ????????????.
the reason is, if we use ? super in collection declaration , the reference can point to same generic type of collection or super generic type of collection. so if we add Animal or subtype of Animal to ? super Animal, the added value(Animal or subtype of it) will pass IS-A test with all types, which are super to Animal.
For example Dog will pass IS-A test with Animal and Object. Below code can explain everything in detail. assume class MyDog extends Dog.
List<? super Dog> list = new ArrayList<dog>(); list.add(new Dog()); list.add(new MyDog()); list = new ArrayList<animal>(); list.add(new Dog()); list.add(new MyDog()); list = new ArrayList<object>(); list.add(new Dog()); list.add(new MyDog());
Now how we can iterate this collection using enhanced for loop. Think about it for a minute, when we are iterating the collection, in for loop reference has to point to an object which is super to Dog so it can be Animal or Object.So we need to use Object because it can hold any other object.
for(Object obj : list){ System.out.println(obj.toString()); }
will produce below output.
Dog MyDog