31

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.

7 Answers 7

31

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.

8
  • 4
    But my question was : why to use generics then ? It can be "Iterable stuff" ... no sense in using wildcards
    – lisak
    Oct 6, 2011 at 7:07
  • 1
    @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. Oct 6, 2011 at 7:10
  • type 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
    Oct 6, 2011 at 7:13
  • 6
    @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 add String then the compiler asks "is String assignable to my type parameter"? If the type parameter is Object or String, 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". Oct 6, 2011 at 7:30
  • 2
    I 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
    – lisak
    Oct 6, 2011 at 7:59
8

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<?>) {
    // ...
}
2
  • 1
    Effective 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 is value instanceof List<?> better than value instanceof List.
    – Joe
    Jan 26, 2016 at 22:55
  • @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".
    – user3453226
    Jan 27, 2016 at 12:51
3

Allow me to rephrase the question:

"What is the difference between List<Object> and List<?> ?"

The answer to that is that List<?> is more restrictive. It tells us that we have a bunch of object of some type, but that type is not necessarily Object.

Since we don't know what that type is, we cannot add to the list at all - anything we add may be of wrong type. In fact, we cannot pass any argument of ? type to any method, not just add().

On the plus side, when we specify that a method takes List<?>, it can take List<String> or List<Integer> or any other List<>. List<Object> can only take List<Object>.

1
  • So the answer is that List<?> is just a short version of List<? extends Object>, right? Mar 9 at 13:23
2

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.

2

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.

0

Using unbounded wildcards only makes sense, AFAIK, when wrapping old code that is not using generics, basically Collections.

If you look at what you can do with such a generic it's basically nothing. If you have a collection you can't add anything, if you try to read something out you will always get an Objectand so on.

This in turns helps guaranteeing that you will handle the data in a type safe way, whereas using the raw type would have caused the compiler to ignore any mess you'd make.

Which methods and fields are accessible/inaccessible through a reference variable of a wildcard parameterized type? from Angelika Langers Java Generics FAQ might be of interest.

0

List<Object> is a List that may contain any Object, e.g. l[0] may be an Integer, l[1] may be a String, etc. List<?> may be a List<Integer> or List<String>, etc. If it is a List<Integer>, it stores only Integers, if it is List<String>, it stores only Strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.