posted 17 years ago
Hi
---------------------------------------------------------------
ArrayList sampleList = new ArrayList<Integer>();// type information is added in object creation
--------------------------------------------------------------
here you can add not only integer ,but also Double,Float,Long,Boolean, what ever it may ,you can add that to the list.It compiles even it runs,but if you try to retrieve the values,then at run time what comes out ? think about this.Here sampleList is not specific to any one like Integer or Double etc.
Generics are for compile time check only.
-----------------------------------------------------------
2) ArrayList<Integer> sampleList = new ArrayList(); // type information is added in reference
-------------------------------------------------------------
Here you can add only integers because you have declared sampleList is of type Integer only and the compiler knows that one.If you try to add any other thing ,the compiler will give compile time error.
-----------------------------------------------------------------
In upper bound(using super) we can add elements I think
------------------------------------------------------------------
Yes we can add elements using super.
for example
class Animal{}
class Dog extends Animal{}
List<Animal> animals = new ArrayList<Animal>();
public void addAnimal(List<? super Dog> animals)
In the above, the list type can be
List<Object> animals or List<Animal> or List<Dog>
because Obect is a super type of all the classes so we can pass.And the runtime object is Animal in the heap.That why we can add.
--------------------------------------------------
But in lower bound(using extends)it is not so
----------------------------------------------
I think now you can understand why this will not work
Thanks
Anil Kumar