Two Laptop Bag
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 REST with Spring (video course) this week in the Spring 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?
Henry Wong

Joined: Sep 28, 2004
Posts: 20374

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
It's not a secret anymore!