This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
ssuchieh li
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 618
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic