Java Reference
In-Depth Information
Diamond Syntax
When creating an instance of a generic type, the right-hand side of the assignment
statement repeats the value of the type parameter. This is usually unnecessary, as the
compiler can infer the values of the type parameters. In modern versions of Java, we
can leave out the repeated type values in what is called diamond syntax .
Let's look at an example of how to use diamond syntax, by rewriting one of our ear‐
lier examples:
// Create a List-of-CenteredCircle using diamond syntax
List < CenteredCircle > shapes = new ArrayList <>();
This is a small improvement in the verbosity of the assignment statement—we've
managed to save a few characters of typing. We'll return to the topic of type infer‐
ence when we discuss lambda expressions towards the end of this chapter.
Type Erasure
In “Default Methods” on page 140 , we discussed the Java platform's strong prefer‐
ence for backwards compatibility. The addition of generics in Java 5 was another
example of where backwards compatibility was an issue for a new language feature.
The central question was how to make a type system that allowed older, nongeneric
collection classes to be used along with newer, generic collections. The design deci‐
sion was to achieve this by the use of casts:
List someThings = getSomeThings ();
// Unsafe cast, but we know that the
// contents of someThings are really strings
List < String > myStrings = ( List < String >) someThings ;
This means that List and List<String> are compatible as types, at least at some
level. Java achieves this compatibility by type erasure . This means that generic type
parameters are only visible at compile time—they are stripped out by javac and are
not reflected in the bytecode. 1
The nongeneric type List is usually called a raw type . It is still
perfectly legal Java to work with the raw form of types—even
for types that are now generic. This is almost always a sign of
poor quality code, however.
The mechanism of type erasure gives rise to a difference in the type system seen by
javac and that seen by the JVM—we will discuss this fully in “Compile and Run‐
time Typing” on page 150 .
1 Some small traces of generics remain, which can be seen at runtime via reflection.
Search WWH ::

Custom Search