• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

doubt in generics

 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
{
System.out.println(no);
}
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


<? 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 ]
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 .....


Yours,
Bu.
 
reply
    Bookmark Topic Watch Topic
  • New Topic