• 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 question List with super

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried this question but I could not find the satisfying explanation of answer of below question.

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);
}

What will be the possible result of the above program?

a) Error at Line 1
b) Error at Line 2
c) Error at Line 3
d) Error at Line 4
e) Compile and execute Sucuessfully
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answer must be d i.e. error at line 4. However I will only explain it after you tell the source of the question...
 
Pandey Gautam
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Answer is right and Source is javabeat.
Could you explain please?
 
Ankit Garg
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well actually when you try to get any element from al, compiler doesn't know the actual type of elements stored in al. It is any super type of Integer.

So if you see the hierarchy Number is a sub-class of Object and Integer is a sub class of Number. So you could also have done this

List <? super Integer> al = new ArrayList<Object>();

then what? what would happen at

for (Number no:al)

it will try to fit an Object into a Number. But this will result in a ClassCastException. This will defeat the whole purpose of Generics (type safety). So whenever you use a <? super Type> syntax, then you can retrieve elements from it only into Object. So this code would work

List <? super Integer> al = new ArrayList<Number>();
al.add(12);
al.add(12+ 13);
for (Object no:al)
{
System.out.println(no);
}
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic