Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in generics

 
anita dhar
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • 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);
}
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • 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 ]
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic