This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

? wildcard in a method declaration

 
Peter Braun
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

java.util.Properties has a method:
public Enumeration<?> propertyNames()

Can you tell me please why does this method use the <?> wildcard in the return type?

Thanks in advance,
Peter
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The <?> type declaration is effectively the same as no type declaration at all, except that it stops the compiler from emitting warnings. (It also lets other developers know that you didn't neglect to use a generic type, you just couldn't narrow it down.) They have to use it in this case because Properties accepts any kind of object as keys.
 
Barry Gold
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wouldn't you get the same result with

public Enumeration<Object> propertyNames() ?

Or does the ? preserve the templateness of the declaration so you can make it more specific later on?
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Barry Gold:
Wouldn't you get the same result with

public Enumeration<Object> propertyNames() ?

Or does the ? preserve the templateness of the declaration so you can make it more specific later on?


No.
Given pre-1.5 type T, which has one paramter (say E):
interface T<E>{}

The pre-1.5 declaration T is (almost) equivalent to the 1.5 declaration T<?>. The problem with a T<Object> is that it is only ever assignable to a T<Object> (and not say a T<String> .

The generics tutorial covers this issue.
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
 
Barry Gold
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I looked in the tutorial and it shows the ? used either as
<? extends T> -- meaning that the (unknown type) is guaranteed to be a descendant of T
or
<? super T> -- meaning that the (unknown type) is guaranteed to be an ancestor of T.

Then comes the section on "wildcard capture", which is no clearer than the previous discussion. So I guess I still don't understand what it's for and exactly what it allows (and doesn't allow).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic