• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

generics ? super Integer

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic