• 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

Java OCP - unbounded wildcard

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

With respect to generics: why should you use an unbounded wildcard?

For example, this method:

seems to act the same as this method:

So why and/or when should I use List<?> in the place of List<T>?

Best regards,
Paul
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe, but tell you what, let's change your methods a little:-. . .Now try executing them.
 
Paul Nijssen
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your quick response Campbell.

In case of using the method with the List<T> argument I can call the add method for the list, but for the method with the List<?> argument I can not call the add method.

When calling add on List<?> the compiler shows some intriguing error message:

The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (T)


So, it seems that the generic type T could not be used to add to the List<?> list. Checking my study guide shows that unbounded generics are immutable so it might be logical that you cannot call add on the List<?> but the error message don't give me a real clue.

I am still a bit confused about when using List<?> and List<T>....
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you have a List<?> is which case you do not at the time know what sort of elements it contains. Remember that whenever you write <T> or <?> or <String>, you are telling the compiler to go into fusspot mode, and if you don't know what sort of elements the List contains, you cannot be certain that adding elements will maintain type‑safety. No type‑safety, no adding.
You will find more useful information in the Java™ Tutorials.
reply
    Bookmark Topic Watch Topic
  • New Topic