File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics question List with super Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Generics question List with super " Watch "Generics question List with super " New topic
Author

Generics question List with super

Pandey Gautam
Greenhorn

Joined: Nov 05, 2008
Posts: 14
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


SCJP6
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9189
    
    2

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Pandey Gautam
Greenhorn

Joined: Nov 05, 2008
Posts: 14
Answer is right and Source is javabeat.
Could you explain please?
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9189
    
    2

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);
}
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Generics question List with super
 
Similar Threads
Adding to generic collection
Generics
<? super Integer>
generics ? super Integer
Generics.....problem