Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt  in generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt  in generics" Watch "doubt  in generics" New topic

doubt in generics

anita dhar
Ranch Hand

Joined: Jul 14, 2007
Posts: 69
can any one explain this code this is from K & b book from genrics self test
List <? super Integer> al = new ArrayList<Number>(); //line 1
al.add12); //line
al.add(12+ 13); //line 3

for (Number no :al) //line
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710

<? super Integer>, you call it lower bound. A reference variable parameterized with lower bound <? super Integer> can refer object of the
class (List implementor class of-course), that is parameterized with Integer
or super class of this as Number and Object.

Lower bound permits you to add objects to the list too, it is not
read only like upper bound <? extends A>.
You can only add object of class Integer to this list, nothing else.

[EDIT] Compiler knows what is returned from the list is Object,
because it could be Integer, Number or Object. Compiler is not sure,
so object is returned.
[ August 02, 2007: Message edited by: Chandra Bhatt ]

Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy ranchers !

In Aneeas code

The bold line cannot compile.
al is of type List <? super Integer>.
The compiler does not know, that an ArrayList<Number> is stored in it.

In al there can be stored lists of Object, Number or Integer. Therefore it must be
for (Object no .....


all events occur in real time
I agree. Here's the link:
subject: doubt in generics
It's not a secret anymore!