• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Mock Question on Generics

 
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks!
I got it.
 
reply
    Bookmark Topic Watch Topic
  • New Topic