my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help with clarity on this Generics question 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 "Help with clarity on this Generics question" Watch "Help with clarity on this Generics question" New topic
Author

Help with clarity on this Generics question

Siphiwe Madi
Ranch Hand

Joined: Aug 16, 2007
Posts: 70
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 ]

Regards, Siphiwe Madi
[SCJP, SCWCD, __] Next ... scjwsd
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
 
subject: Help with clarity on this Generics question