Java Reference
In-Depth Information
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 preced-
ing program, these lines generate unchecked warnings:
In the first line, it is the use of Gen 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.
At first, you might think that this line should also generate an unchecked warning, but it
does not:
No compiler warning is issued because the assignment does not cause any further loss of
type safety than had already occurred when raw was created.
One final point: You should limit the use of raw types to those cases in which you must
mix legacy code with newer, generic code. Raw types are simply a transitional feature and
not something that should be used for new code.
Type Inference with the Diamond Operator
Beginning with JDK 7, it is possible to shorten the syntax used to create an instance of a
generic type. To begin, think back to the TwoGen class shown earlier in this chapter. A
portion is shown here for convenience. Notice that it uses two generic types.
Search WWH ::




Custom Search