What is <?> in Java

CrazYmonkeY159

Expert Member
Joined
Sep 13, 2007
Messages
2,142
Reaction score
0
Location
CPT/PE
So I was finding out how to schedule a timed process in java all is well and I discovered this


There is a LOC which reads

Code:
final ScheduledFuture<?> beeperHandle =

What is the <?> for? I know that the angled brackets are used in generics a lot on Java but what does this line of code actually mean.

I pretty much understand the gist of the code, but that particular LOC is not all that clear to me.
 
That class is generic and the ? means anything, essentially equivalent to Object. The reality is Java doesn't know the type of generic at runtime because of type erasure. You use the ? wildcard for more control over what would give you compilation errors (because type checking is done at compile time for generics).

Type erasure is also the reason the following is not possible:
Code:
public <T> T[] test(T someObj) {
T[] someArr = new T[5];
someArr[0] = someObj;
return someArr;
}

You can also do ScheduledFuture<? implements Comparable> for any Object that implements Comparable.

EDIT: http://en.wikipedia.org/wiki/Generics_in_Java#Type_wildcards

They explain it better :)

Especially have a look at type erasure in Java generics to get a complete feel for exactly how generics work.
 
Last edited:
Gnome, I'm not sure if you can do "<? implements C>" !?
I know you can do "<? extends T>".
 
Gnome, I'm not sure if you can do "<? implements C>" !?
I know you can do "<? extends T>".

You are right (just did a quick test), even for an interface (eg Comparable) you have to use the extends. Normally that would be a compile error given it is impossible to actually extend an interface.
 
Top
Sign up to the MyBroadband newsletter
X