• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with clarity on this Generics question

 
Siphiwe Madi
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

This question if from a Mock exam by John Meyers.

Can you please clariry why the correct answer says the Line marked // 2 will not Compile and the return type of this method is List<T>.

My understanding was the code would compile jus fine.


public <T> List<T> meth(List<?> type)
{
System.out.println(type); // 1
return new ArrayList<String>(); // 2
}

Thanks in advance.

Regards,
Siphiwe Madi
[ November 14, 2008: Message edited by: Siphiwe Madi ]
 
Ankit Garg
Sheriff
Posts: 9529
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Siphiwe the code will not compile. The method itself cannot decide what is the type of T. It returns a List of type T. But the method itself doesn't know the type of T. It depends on the calling code.

If the call is

List<Integer> l = obj.meth(new List<String>());

then the type of T will resolve to Integer. And if the call is

List<String> l = obj.meth(new List<Object>());

then the type of T will resolve to String...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic