Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics ? super Integer

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21385
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic