开发者

What is the use and point of unbound wildcards generics in Java?

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 generi开发者_如何转开发cs? Compiler doesn't find any conflict and after type erasure it would be like no generics was used.


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.


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<?>) {
    // ...
}


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.


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.


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>.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜