Monday, April 30, 2007

Java: bounded wildcards

The Java Tutorials > Bonus > Generics > Wildcards

public void drawAll(List shapes) {
...
}

There is a small but very important difference here: we have replaced the type List with List. Now drawAll() will accept lists of any subclass of Shape, so we can now call it on a List if we want.

List is an example of a bounded wildcard. The ? stands for an unknown type, just like the wildcards we saw earlier. However, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.) We say that Shape is the upper bound of the wildcard.

There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:

public void addRectangle(List shapes) {
shapes.add(0, new Rectangle()); // Compile-time error!
}

You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape-- an unknown subtype of Shape. Since we don't know what type it is, we don't know if it is a supertype of Rectangle; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.


On the other hand, if you specify the upper bound of the wildcard, it's okay to add items to the List shapes.

Labels: ,

0 Comments:

Post a Comment

<< Home