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 Barcodes with iOS this week in the iOS forum
or Core Java for the Impatient in the Java 8 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: 19306
    
  41

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)
 
Consider Paul's rocket mass heater.
 
subject: generics ? super Integer