aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why can I have  List o = new LinkedList<?>(); Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why can I have  List o = new LinkedList<?>();" Watch "why can I have  List o = new LinkedList<?>();" New topic
Author

why can I have List o = new LinkedList<?>();

ssuchieh li
Greenhorn

Joined: May 01, 2010
Posts: 6
Please Explain why I can't initialize List o = new LinkedList<?>();
but I could use List<?> as the parameter decoration in a method.

Thank you so much,

Jessy
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
When creating an instance as you suggested:What would it mean? That you want to create an instance of a LinkedList that can hold anything? This is exactly what generics is preventing.
Kevin Kilbane
Ranch Hand

Joined: Sep 22, 2008
Posts: 42
ssuchieh li wrote:Please Explain why I can't initialize List o = new LinkedList<?>();
but I could use List<?> as the parameter decoration in a method.

Thank you so much,

Jessy


Please note: in my answer "object" (small o) refers to any object on the heap e.g. String, Object, Integer etc. whereas "Object" (capital O) refers to an object of type Object i.e Object.class.

The wildcard (the question mark) can only be used for references not for objects.

List<?> is the same as List<? extends Object> so the reference o in your example can point to any List object where the elements of that List are Objects or sub-classes of Object. But the actual List object that the reference points to i.e. the List created by using the "new" keyword has to have elements of a definite type (and that type has to be Object or one of it's sub-classes in your example (which is of course any object)).

The reason you can pass List<?> as a parameter to a method is because all you are doing is passing a reference to a List object, you are not passing an actual object. At some stage the object that this reference points to will have been created on the heap i.e. at some stage the "new" keyword would have been used and, at that stage, the generic type of the List object would have been specified:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why can I have List o = new LinkedList<?>();