2.8 Generics and Type Conversions
Now that you have all your
nifty parameterized types, you'll probably
want to perform all sorts of nifty type conversions. This List of Integers
gets tossed into that Map of Numbers...then again, it's not quite that easy.
You'll need to take great care if you want these conversions to actually
work.
2.8.1 How do I do that?
The key in casting generic types is to understand that as with normal,
non-generic types, they form a hierarchy. What's unique about generics,
though, is that the hierarchy is based on the base type, not the parameters
to that type. For example, consider this declaration:
LinkedList<Float> floatList = new LinkedList<Float>( );The conversion is based on LinkedList, not
Float. So this is legal:
List<Float> moreFloats = floatList;However, the following is not:
LinkedList<Number> numberList = floatList;While Float is indeed a subclass of Number, it's the generic type that is
important, not the parameter type.
2.8.2 What just happened?
There are two key things to understand if you want to know why type
conversions work like this; the first is seeing how type conversions can
be abused, and the second is erasure. First, consider this sample code,
which is actually illegal in Tiger; it demonstrates why converting a
LinkedList<Float> to a LinkedList<Number> (or even to a
LinkedList<Object>) should indeed be illegal:
List<Integer> ints = new ArrayList<Integer>( );Clearly, it needs to be the base type that is considered in type conversions,
ints.add(1);
ints.add(2);
// This is illegal, but use it for illustration purposes
List<Number> numbers = ints;
// Now a float is being added to a list of ints! This results in a
// ClassCastException when the item is retrieved from the
// list and used as an int (instead of a float)
numbers.add(1.2);
// This is even worse
List<Object> objects = ints;
objects.add("How are you doing?");
not the parameter type.The second concept you'll want to grasp is erasure. Generics in Tiger is a
compile-time process, and all typing information is handled at compiletime.
Once the classes are compiled, the typing information is erased
(thus the term erasure). Consider the following two declarations:
List<String> strings = new LinkedList<String>( );This information is used at compile-time to perform type-checking, but
List<Integer> ints = new LinkedList<Integer>( );
then the typing information is dropped out at runtime. So, to the JVM,
these declarations actually become:
List strings = new LinkedList( );The type parameters are gone, now. With that in mind, consider this
List ints = new LinkedList( );
(illegal) cast:
List<Integer> ints = new LinkedList<Integer>( );While this may look OK at compile-time, at runtime there are simply two
List<Number> nums = ints;
lists, one trying to be cast to the otherwithout any type-safety in play
at all. Again, then, the compiler does the right thing by using the base
type, rather than the parameterized type, for cast checks.
2.8.3 What about...
NOTESome folks get upset that parameterization is only a compiletime thing. A worthy gripe, but something (compile-time checking) is almost always better than nothing....defeating type-safety? Well, when you understand the reasons for casting
restrictions and erasure, it actually becomes pretty easy to get around
type checking. First, for backwards-compatibility, you can always cast a
parameterized type to a raw typethat is, a generic type with no parameterization:
List<Integer> ints = new LinkedList<Integer>( );This obviously leads to a ClassCastException at runtime, but it compiles
// We can widen (due to backwards compatibility)
List oldList = ints;
// This line should be illegal, but it happily compiles and runs
oldList.add("Hello");
// Here's the problem!
Integer i = ints.get(0);
just fine. You'll get an unchecked warning (if you're compiling under Tiger), but that's it.You can also use erasure
to break type-safety. Remember that at runtime,
erasure removes
all your parameterization. This means that when you
access parameterized types with reflection, you get the effects of erasure,
at compile-time (Example 2-1):
Example 2-1. Breaking type safety with reflection
package com.oreilly.tiger.ch02;When list is assigned the reference of the ints List, it does not have
import java.util.ArrayList;
import java.util.List;
public class BadIdea {
private static List<Integer> ints = new ArrayList<Integer>( );
public static void fillList(List<Integer> list) {
for (Integer i : list) {
ints.add(i);
}
}
public static void printList( ) {
for (Integer i : ints) {
System.out.println(i);
}
}
public static void main(String[] args) {
List<Integer> myInts = new ArrayList<Integer>( );
myInts.add(1);
myInts.add(2);
myInts.add(3);
System.out.println("Filling list and printing in normal way...");
fillList(myInts);
printList( );
try {
List list = (List)BadIdea.class.getDeclaredField("ints").get(null);
list.add("Illegal Value!");
} catch (Exception e) {
e.printStackTrace( );
}
System.out.println("Printing with illegal values in list...");
printList( );
}
}
the Integer restriction that the ints member variable does. As a result,
adding a String value (like "Illegal Value!") is perfectly legalerasure has
removed any parameterization. It's only at runtime, when iterating over
the list and printing it, that the problem shows up.