• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic