| 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
|
|
|
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
|
|
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); }
|
 |
 |
|
|
subject: Generics question List with super
|
|
|