aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock Question on Generics" Watch "Mock Question on Generics" New topic
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
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Mock Question on Generics
 
Similar Threads
Generics question?
John Meyers's SCJP mock errata
Help with clarity on this Generics question
generics
Genericss