aspose file tools*
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 Spring in Action this week in the Spring 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?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  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)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generics ? super Integer