File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock Question on Generics

 
M Srilatha
Ranch Hand
Posts: 137
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Thomas Thevis
Ranch Hand
Posts: 87
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ankit Garg
Sheriff
Posts: 9497
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
M Srilatha
Ranch Hand
Posts: 137
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
I got it.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic