Wildcards with Generics
by , 11-29-2011 at 11:16 PM (1654 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.
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 NonCovariantGenerics { // Compile Error: incompatible types: List<Shape> slist = new ArrayList<Rectangle>();
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."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); } }
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.









Email Blog Entry
you can develop me for me (adf.ly...
Today, 08:20 AM in Java Software