• 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

Generic Confusion

 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Guys,

Need help from you, can anyone break down the following code and explain to me why? This is from John Meyers' question.

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

The answer is is fail compilation on line 2

Why?
 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Henry,

List<T> is the return type of the method. Since T(which stands for Type) can be any type (for eg. T can be Object, or Vector, or JButton etc.), the method cannot return an ArrayList<String>. If the method returns ArrayList<T>, the code would compile perfectly.

Kind Regards,
Rakesh.R
SCJP 6, SCWCD 5.
[ November 07, 2008: Message edited by: Rakesh Rajagopalan ]
 
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
Well actually the method meth cannot decide what T stands for. It depends on the calling code. If the call is like this

List<Integer> list = obj.meth(new ArrayList());

Then the compiler would say that T is Integer. So the method meth is in complete darkness about the type of T. It depends on the calling code about the type of T. So it cannot say that T is String...
 
Henry Zhi Lin
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Clear enough, thanks for you guys.
 
get schwifty. tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic