• 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

what is the use of the following wildcard notation?

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the following code i never see any usage of it...can anyone show me some example?
 
Author
Posts: 836
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is it you don't understand here? Ignore the generics for a second and you've got "List y = new ArrayList()" which is fine since List is a superclass of ArrayList. Now put the generics back and Number is assignable to the generic type ? since the ? is a wildcard.

What we're saying is: ArrayList<Number> is an ArrayList holding only Number (or subclass) instances. List<?> is some List implementation which holds any type of element (this is quite an abstract concept!). As usual with unbounded wildcards, you can retrieve or remove any elements from the list but cannot add anything (since we don't know the specific type of the actual list).

This is most useful when you've got a method which can accept Lists with arbitrary contents and whose contents only need to be accessed - methods in the Collections API such as swap/convert to array use these ideas. Take a look at the docs for some classes in java.util.

Does that help?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic