• 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

Question about Generics and <? extends T>

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why the following code compiles and runs?

Backwards accepts any List of type <? extends T> but T is not defined yet...

It looks like that when you call backwards(list) T becomes a String, but why? it could become even an Object!

The only diffence I can see using backwards(List<? extends T> or backwards(List<T> is that with the first approach I cannot add anything to the list I pass to the backwards method...

Any help would be appreciated!


 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think if you don't use the type in the method call, object is inferred as the type. So your local type variable points
to a String instance (because the content of list is a String instance).

cheers
Bob
 
Ranch Hand
Posts: 282
Eclipse IDE PHP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Massimo Battestini wrote:It looks like that when you call backwards(list) T becomes a String, but why?


When you call backwards(), it sees that you're passing in a List<String>, so it's able to infer that you want T to be a String. So the following two method calls are the same:

Because the parameter of backwards() uses a wildcard, you could also do something like this:
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

As an aside, not really an answer to this question... You do know that you can't determine the type of T with this line.



Generic types are erased at runtime, so all this line does is tell you what object types are in the list -- no the generic type T of the list. If you had declared the list of type Object, and placed nothing but strings, then this instanceof condition would still succeed.

Henry
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic