View RSS Feed

Advanced Java

Wildcards with Generics

Rate this Entry
by , 11-29-2011 at 11:16 PM (2452 Views)
Unlike with arrays, it is important to remember with generics that is not possible to upcast an object from its superclass to its subclass. So for example, this will create a compile time error.

Java Code:
import java.util.*;

public class NonCovariantGenerics { 
// Compile Error: incompatible types: 
List<Shape> slist = new ArrayList<Rectangle>();
In this listing List of Rectangle is not type-equivalent to a List of Shape, even if an Rectangle is a kind of Shape. So sometimes if you would like to establish this kind of upcasting relationship between the two, so that is the purpose of wildcards.

Java Code:
import java.util.*;
public class GenericsAndCovariance { 
   public static void main(String[] args) {
      // Wildcards allow covariance: 
      List<? extends Shape> 
      slist = new ArrayList<Rectangle>(); 
      // Compile Error: canít add any type of object: // 
      slist.add(new Rectangle()); 
      slist.add(new Shape());  
      slist.add(new Object()); 
      slist.add(null); 
      // Legal but uninteresting 
      // We know that it returns at least a Shape: 
      Shape s = slist.get(0);
   } 
}
The type of slist is now List<? extends Shape>, which you can read as "a list of any type thatís inherited from Shape." This doesnít actually mean that the List will hold any type of Fruit, however. The wildcard refers to a definite type, so it means "some specific type which the slist reference doesnít specify." So the List thatís assigned has to be holding some specified type such as Shape or Rectangle, but in order to upcast to slist, that type is a "donít actually care."

On the other hand, if you call a method that returns Shape, thatís safe because you know that anything in the List must at least be of type Shape, so the compiler allows it.

Submit "Wildcards with Generics" to Facebook Submit "Wildcards with Generics" to Digg Submit "Wildcards with Generics" to del.icio.us Submit "Wildcards with Generics" to StumbleUpon Submit "Wildcards with Generics" to Google

Comments