File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes ? wildcard in a method declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "? wildcard in a method declaration" Watch "? wildcard in a method declaration" New topic
Author

? wildcard in a method declaration

Peter Braun
Ranch Hand

Joined: Feb 09, 2005
Posts: 57
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

Joined: May 06, 2004
Posts: 262
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

Joined: Dec 15, 2005
Posts: 22
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

Joined: Sep 24, 2003
Posts: 1608
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


Tony Morris
Java Q&A (FAQ, Trivia)
Barry Gold
Greenhorn

Joined: Dec 15, 2005
Posts: 22
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).
 
Consider Paul's rocket mass heater.
 
subject: ? wildcard in a method declaration
 
Similar Threads
Generic Array Creation
What is greater than less than?
Need generic clarification
bounded wild card - confusion
Generics: Wildcard capture