| Author |
Mock Question on Generics
|
M Srilatha
Ranch Hand
Joined: Aug 27, 2008
Posts: 137
|
|
Hi All, The following mock question is from http://enigma.vm.bytemark.co.uk/webstart.html
public <T> List<T> meth(List<?> type) { System.out.println(type); // 1 return new ArrayList< String>(); // 2 }
This code doesnt compile because of 2 line. And the error message is Type mismatch: cannot convert from ArrayList<String> to List<T>. As per my knowledge, return type List<T> means the method can return a collection of type List or any subtype of List. But the code here doesnt compile! Could you please explain why the compiler error occurs?
|
Thanks,<br />Srilatha M
|
 |
Thomas Thevis
Ranch Hand
Joined: Sep 02, 2008
Posts: 87
|
|
The problem is not the ArrayList subtype of List, but the generic parameter <T>. You cannot simply return a List of generic type String. Regards, Thomas
|
SCJP 5.0, SCJD in progress
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
When you write List<T> it means that you can return List or its sub-type which are typed as T. But T is not necessarily String. This is why returning return ArrayList<String> gives you an error as <T> might not always be <String>. Even if you write List<String>, then also it will give you an error...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
M Srilatha
Ranch Hand
Joined: Aug 27, 2008
Posts: 137
|
|
Thanks! I got it.
|
 |
 |
|
|
subject: Mock Question on Generics
|
|
|