Java Reference
In-Depth Information
casted to their specific type, often after testing with the instanceof operator. A key benefit
of Generic Types is that they obviate this testing and downcasting by doing more work at
compile time. The casting is still done at runtime, but it disappears from your attention.
You can still instantiate classes such as ArrayList without using a specific type. In this case,
they behave as in the old days—that is, the objects returned from a Collection or Iterator
are treated as of type java.lang.Object and must be downcast before you can call any
application-specific methods or use them in any application-specific method calls.
As a further example, consider the Map interface mentioned in Chapter 7 . A Map requires a
key and a value in its put() method. A Map , therefore, has two parameterized types. To set
up a Map whose keys are Person objects and whose values are Address objects (assuming
these two classes exist in your application), you could define it as:
Map<Person, Address> addressMap = new HashMap<>( );
This Map expects a Person as its key and an Address as its value in the put() method; the
get() method returns an Address object, the keySet() method returns Set<Person> (i.e., a
Set specialized for Person objects), and so on.
See Also
Although the generics avoid your having to write downcasts, the casts still occur at runtime;
they are just provided by the compiler. The compiler techniques used in compiling these new
constructs in a backward-compatible way include erasure and bridging , topics discussed in
an article by O'Reilly author William Grosso.
Avoid Casting by Using Generics
Problem
You wish to define your own container classes using the Generic Type mechanism to avoid
needless casting.
Search WWH ::




Custom Search