File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "generics ? super Integer" Watch "generics ? super Integer" New topic

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

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

Joined: Sep 28, 2004
Posts: 18103

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: generics ? super Integer
Similar Threads
Adding to generic collection
doubt in generics
Generics question List with super
<? super Integer>