Notice that no type arguments are specified. In essence, this creates a Gen object whose
type T is replaced by Object.
A raw type is not type safe. Thus, a variable of a raw type can be assigned a reference to
any type of Gen object. The reverse is also allowed; a variable of a specific Gen type can be
assigned a reference to a raw Gen object. However, both operations are potentially unsafe
because the type checking mechanism of generics is circumvented.
This lack of type safety is illustrated by the commented-out lines at the end of the program.
Let's examine each case. First, consider the following situation:
//
int i = (Integer) raw.getob(); // run-time error
In this statement, the value of ob inside raw is obtained, and this value is cast to Integer.
The trouble is that raw contains a Double value, not an integer value. However, this cannot
be detected at compile time because the type of raw is unknown. Thus, this statement fails
at run time.
The next sequence assigns to a strOb (a reference of type Gen<String>) a reference to
a raw Gen object:
strOb = raw; // OK, but potentially wrong
//
String str = strOb.getob(); // run-time error
The assignment, itself, is syntactically correct, but questionable. Because strOb is of type
Gen<String>, it is assumed to contain a String. However, after the assignment, the object
referred to by strOb contains a Double. Thus, at run time, when an attempt is made to assign
the contents of strOb to str, a run-time error results because strOb now contains a Double.
Thus, the assignment of a raw reference to a generic reference bypasses the type-safety
mechanism.
The following sequence inverts the preceding case:
raw = iOb; // OK, but potentially wrong
//
d = (Double) raw.getob(); // run-time error
Here, a generic reference is assigned to a raw reference variable. Although this is syntactically
correct, it can lead to problems, as illustrated by the second line. In this case, raw now refers
to an object that contains an Integer object, but the cast assumes that it contains a Double.
This error cannot be prevented at compile time. Rather, it causes a run-time error.
Because of the potential for danger inherent in raw types, javac displays unchecked warnings
when a raw type is used in a way that might jeopardize type safety. In the preceding program,
these lines generate unchecked warnings:
Gen raw = new Gen(new Double(98.6));
strOb = raw; // OK, but potentially wrong
In the first line, it is the call to the Gen constructor without a type argument that causes the
warning. In the second line, it is the assignment of a raw reference to a generic variable that
generates the warning.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home