File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about Generics and <? extends T> 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 "Question about Generics and <? extends T>" Watch "Question about Generics and <? extends T>" New topic

Question about Generics and <? extends T>

Massimo Battestini

Joined: Nov 21, 2008
Posts: 11
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

Joined: Apr 24, 2009
Posts: 317
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).


JavaEnterpriseEditionFaq - TomcatFaq
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 277

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

Joined: Sep 28, 2004
Posts: 20521

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Don't get me started about those stupid light bulbs.
subject: Question about Generics and <? extends T>
It's not a secret anymore!