• 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

Troubling T's

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


I interpret this ugly method signature as a public method that returns a List of some type <T> and takes some List of any type.

I'm told that this code does not compile because a List is required at //2. OK, this makes sense because, as I interpreted, the ugly method returns a List of some type.

Now the ugly signature changes:


And here the method will return a List of any type. I'm told this code is OK because a List<?> will expect any Object.

I tested these findings and sure enough, the first code sample does not compile for the reasons stated and the second code sample compiles cleanly.

Can someone please help me understand why the second code sample compiles while it is returning the same ArrayList as the first code sample, which does not compile? Isn't it true that a "List<?>" and a "List<T>" are both Lists? Why is it legal to return an ArrayList on a method defined with "List<?>" and not on a method defined with "List<T>"? What am I failing to understand?

Thank you for your clarification(s).
Gary
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Returning ArrayList is not the problem.... an ArrayList IS A List & can be retuned - BUT the problem here is :
In the first method the return type is declared as List<T> ; So only & only List<T> can be returned there. At compile time one can not be sure that List<T> might be a List<String>

In the second case return type is List<?> that means List of anything that extends Object & can thus return List<String>
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic