Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about Generics and <? extends T>

 
Massimo Battestini
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • 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!


 
Bob Wheeler
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • 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
 
Michael Angstadt
Ranch Hand
Posts: 277
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • 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:
 
Henry Wong
author
Marshal
Pie
Posts: 21364
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic