posted 15 years ago
Well actually when you try to get any element from al, compiler doesn't know the actual type of elements stored in al. It is any super type of Integer.
So if you see the hierarchy Number is a sub-class of Object and Integer is a sub class of Number. So you could also have done this
List <? super Integer> al = new ArrayList<Object>();
then what? what would happen at
for (Number no:al)
it will try to fit an Object into a Number. But this will result in a ClassCastException. This will defeat the whole purpose of Generics (type safety). So whenever you use a <? super Type> syntax, then you can retrieve elements from it only into Object. So this code would work
List <? super Integer> al = new ArrayList<Number>();
al.add(12);
al.add(12+ 13);
for (Object no:al)
{
System.out.println(no);
}