File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

Question about Generics and <? extends T>

Massimo Battestini
Greenhorn

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).

cheers
Bob


SCJP 6 - SCJD - SCWCD 5 - SCBCD 5
JavaEnterpriseEditionFaq - TomcatFaq
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 274

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:


SCJP 6 || SCWCD 5
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40


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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about Generics and <? extends T>