This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes generics ? super Integer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "generics ? super Integer" Watch "generics ? super Integer" New topic
Author

generics ? super Integer

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
List <? super Integer> al = new ArrayList<Number>(); //line 1
al.add(12); //line 2
al.add(12+ 13); //line 3
for (Number no:al) //line 4
{System.out.println(no);}


is there an error at line 4?
and why is it?


boolean b = true;<br />System.out.println ("I believe in Java.<br />Java will make my dream come " + b);
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18507
    
  40

Originally posted by adam lui:
is there an error at line 4?
and why is it?



Basically, al is a list that holds Integer or any it's super classes. This means that the list can hold Object, Number, or Integer instances.

In line 4, you are assigning the elements of the list to Number reference. Unfortunately, since Object instances can't be assigned to a Number reference (without a cast), the compiler will report it as an error.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: generics ? super Integer
 
Similar Threads
<? super Integer>
doubt in generics
Adding to generic collection
Generics question List with super
Generics