View RSS Feed

Advanced Java

Supertype Wildcards with Generics

Rate this Entry
by , 11-29-2011 at 11:12 PM (1790 Views)
In my last tip, I showed how you can use a wildcard with generics. It is also possible to use a supertype wildcards. In this case the wildcard is bounded by any base class of a particular class, by specifying <? super MyClass> or even using a type parameter: <? super T> (although you cannot give a generic parameter a supertype bound; that is, you cannot say <T super MyClass>). This allows you to safely pass a typed object into a generic type. Thus, with supertype wildcards you can write into a Collection:

Java Code:
import java.util.*;
public class SuperTypeWildcards { 
   static void writeTo(List<? super Rectangle> rectangles) {
      rectangles.add(new Rectangle()); 
      rectangles.add(new SubOfRectangle()); 
      rectangles.add(new Shape()); 
The argument rectangles is a List of some type that is the base type of Rectangle; thus you know that it is safe to add an Rectangle or a subtype of Rectangle. Since the lower bound is Rectangle, however, you donít know that it is safe to add Shape to such a List, because that would allow the List to be opened up to the addition of non-Rectangle types, which would violate static type safety.
You can thus begin to think of subtype and supertype bounds in terms of how you can "write" (pass into a method) to a generic type, and "read" (return from a method) from a generic type.

Submit "Supertype Wildcards with Generics" to Facebook Submit "Supertype Wildcards with Generics" to Digg Submit "Supertype Wildcards with Generics" to Submit "Supertype Wildcards with Generics" to StumbleUpon Submit "Supertype Wildcards with Generics" to Google