Wednesday, May 6, 2009

Parameterized types and bounded wildcards

We know that parameterized types (in Java) are invariant, which implies that, for example, even though Integer is a subtype (subclass) of Number, List is not a subtype of List. Let's see how this impacts you code. Assume we have a class named Bucket declared below:

public class Bucket {
   public void add(E e){...};
   public void addAll(List list){
      for(E e : list) {
         add(e);
      }
   }
}

If you would try to do the following:

Bucket numberBucket = new Bucket();
List integers = new ArrayList();
...
numberBucket.addAll(integers);

you get the error:

The method addAll(List) in the type Bucket is not applicable for the arguments (List).

How can we get out of this? Easy, by using a bounded wildcard type:

public void addAll(List list){
   for(E e : list) {
      add(e);
   }
}

No comments: