Datasheet

objectHolder.putItem(str);
str2 = stringHolder.getItem();
//str2 = objectHolder.getItem();
}
Look at the last two lines. Retrieving an element from stringHolder and assigning it to a string is fine.
However, if you uncomment the second line, which tries to access the same string in the
objectHolder,
you get the following compiler error.
c:\>javac CustomHolder.java
CustomHolder.java:28: incompatible types
found : java.lang.Object
required: java.lang.String
str2 = objectHolder.getItem();
^
1 error
This makes sense because the actual type parameter (in this case, String or Object) dictates the type.
When you add a
String to the objectHolder, it is simply stored as an Object. When you attempt to
assign the
Object to the String (in the call to objectHolder.getItem), you now need an explicit cast
to the
String type.
Because of type erasure, it is possible to assign a generic class reference to a reference of its nongeneric
(legacy) version. Therefore, the following code compiles without error:
Vector oldVector;
Vector<Integer> intVector;
oldVector = intVector; // valid
However, though not an error, assigning a reference to a nongeneric class to a reference to a generic class
will cause an unchecked compiler warning. This happens when an erasure changes the argument types
of a method or a field assignment to a raw type if the erasure changes the method/field type. As an
example, the following program causes the warnings shown after it. You must pass
-Xlint:unchecked
on the command line to javac to see the specific warnings:
import java.util.*;
public class UncheckedExample {
public void processIntVector(Vector<Integer> v)
{
// perform some processing on the vector
}
public static void main(String args[])
{
Vector<Integer> intVector = new Vector<Integer>();
Vector oldVector = new Vector();
UncheckedExample ue = new UncheckedExample();
// This is permitted
10
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 10