What is the use and point of unbound wildcards generics in Java?
Solution 1
An unbound type can be useful when your method doesn't really care about the actual type.
A primitive example would be this:
public void printStuff(Iterable<?> stuff) {
for (Object item : stuff) {
System.out.println(item);
}
}
Since PrintStream.println()
can handle all reference types (by calling toString()
), we don't care what the actual content of that Iterable
is.
And the caller can pass in a List<Number>
or a Set<String>
or a Collection<? extends MySpecificObject<SomeType>>
.
Also note that not using generics (which is called using a raw type) at all has a quite different effect: it makes the compiler handle the entire object as if generics don't exist at all. In other words: not just the type parameter of the class is ignored, but also all generic type parameters on methods.
Another important distinctions is that you can't add any (non-null
) value to a Collection<?>
, but can add all objects to the raw type Collection
:
This won't compile, because the type parameter of c
is an unknown type (= the wildcard ?
), so we can't provide a value that is guaranteed to be assignable to that (except for null
, which is assignable to all reference types).
Collection<?> c = new ArrayList<String>();
c.add("foo"); // compilation error
If you leave the type parameter out (i.e. use a raw type), then you can add anything to the collection:
Collection c = new ArrayList<String>();
c.add("foo");
c.add(new Integer(300));
c.add(new Object());
Note that the compiler will warn you not to use a raw type, specifically for this reason: it removes any type checks related to generics.
Solution 2
When you need to perform an instanceof
check.
You can't parameterize like this:
Object value;
if (value instanceof List<String>) {
// ...
}
So you do:
Object value;
if (value instanceof List<?>) {
// ...
}
Solution 3
While using raw types means that you don't know about generics (because you're lazy or code was written ages ago), using <?>
means that you know about generics and explicitly emphasize that your code can work with any kind of objects.
Solution 4
There are (rare) perfectly correct use cases for unbound wildcards. The SDK contains some of them.
One example is a method that does a definite action on a list of any kind and does not return anything as rotate
in Collections
:
static void rotate(List<?> list, int distance)
Another example is when you want to list the possible constructors for a class, the method is :
Constructor<?>[] getConstructors()
Here it in not even possible to use a generic, because by definition the array will contain different constructor each with its own actual class. By contrast, the API does use a generic signature for getting one single constructor : Constructor<T> getConstructor(Class<?>... parameterTypes)
.
The conclusion is that even if it is mainly used for compatibility with older code, there are still places where unbound wildcard generics are the correct way.
Comments
-
lisak almost 2 years
I don't understand what is the use of unbound wildcards generics. Bound wildcards generics with upper boundary
<? extends Animal>
makes perfect sense, because using polymorphism I can work with that type or collection. But what is the point of having generics that can be of any type? Doesn't it defeat the purpose of generics? Compiler doesn't find any conflict and after type erasure it would be like no generics was used. -
lisak over 12 yearsBut my question was : why to use generics then ? It can be "Iterable stuff" ... no sense in using wildcards
-
Joachim Sauer over 12 years@Edgar: because a raw type (without generics) only exists for backwards compatibility: it effectively turns off all type checks for that type. While using a wildcard still does the type checks, but against an unkown type.
-
lisak over 12 yearstype check against an unknown type ? I don't get the last sentence in your answer "you can't add any (non-null) value to a Collection<?>, but can add all objects to the raw type Collection"
-
lisak over 12 yearsman I'm really trying to understand why it doesn't compile. There is a wildcard (any type / subtype of object) so it should be assigned a String right ? Why the compiler rejects to compile it ?
-
Joachim Sauer over 12 years@Edgar:
?
doesn't just mean "I don't care". It means "some specific type, but I don't know which one". If you try to addString
then the compiler asks "isString
assignable to my type parameter"? If the type parameter isObject
orString
, then the answer is "yes". If the type parameter is "some specific type, but I don't know which one", then the answer is "I don't know!" which will be treated as if it were a "no". -
lisak over 12 yearsI get it, it's hard to explain, but I see its purpose perfectly now. I've been using wildcards for a long time intuitively without even thinking about it much... thanks
-
stephenbez about 9 yearsWhy do
public void printStuff(Iterable<?> stuff)
instead ofpublic <E> void printStuff(Iterable<E> stuff)
? -
Joe over 8 yearsEffective Java 23 says
instanceof
checks are an acceptable use case for raw types, e.g.value instanceof List
is okay. Is there any advantage to using an unbounded wildcard versus a raw type? Stated another way, why isvalue instanceof List<?>
better thanvalue instanceof List
. -
spongebob over 8 years@JoeS There's no difference at runtime actually. I would recommend using the wildcard to make it clear that it is a "list of anything".
-
shawn1874 over 5 yearsJust curious. What's the difference between that and the following. public static <T> void printStuff(Iterable<T> stuff) { for (Object item : stuff) { System.out.println(item); } }