File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mock Question on Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock Question on Generics" Watch "Mock Question on Generics" New topic

Mock Question on Generics

M Srilatha
Ranch Hand

Joined: Aug 27, 2008
Posts: 137
Hi All,

The following mock question is from

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.


SCJP 5.0, SCJD in progress
Ankit Garg

Joined: Aug 03, 2008
Posts: 9462

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
I got it.
I agree. Here's the link:
subject: Mock Question on Generics
It's not a secret anymore!