Jagat Sastry wrote: have read that the following code snippet will result in a compiler error
For the purpose of the exam, if you are given a list with <? extends aType> , never try to add anything to the list as you will get a compilation error.
Reason: List <? extends SuperType> alist can be assigned to ArrayList<SuperType> or ArrayList< anySubType>. For example, List<? extends Animal> = new ArrayList<Animal> orArrayList<Cat> and etc.
When the compiler "sees" the tryAddingToList methods , the compiler does not know what list exactly contains. The list can have a list of SuperType or some subtypes of it.
Since the compiler does not know what list exactly has, it cannot add anything to it. Therefore list.add(null) is the only valid statement you can have.
On the other hand, how about this?
The only type this list can accept is SuperType or its super type
List<? super SuperType> list= new ArrayList<SuperType>() ; or
List<? super SuperType> list = new ArrayList<Object>();
The compiler knows list contain either SuperType or its super type or Object. But it does not know what it is exactly.
The compiler can only accept list.add(new SuperType()), not other types.
For example, list can be assigned to :
Case 1: List<? super Mammal> list = new ArrayList<Mammal>();
Case 2: List<? super Mammal> list = new ArrayList<Animal>();
Case 3: List<? super Mammal> list = new ArrayList<Object>();
What can we add to list inside your tryAddingToList () method? Only Mammal type!
Why the compiler prevents you from adding Animal or Object to list?
Reason: the compiler does not know what exactly list contains in compile time. The compiler says to you "Hey, programmer, I only know list contains Mammal or its super type. of Animal that are not mammal. What happens if you pass in the list in case 3, but you have Object o = new Integer(10) and add o to your list? Your list contains a type of Mammal or its super type, Integer is not in the inheritance hierarchy. "