Java Reference
In-Depth Information
Type erasure also prohibits some other definitions, which would otherwise seem
legal. In this code, we want to count the orders as represented in two slightly differ‐
ent data structures:
// Won't compile
interface OrderCounter {
// Name maps to list of order numbers
int totalOrders ( Map < String , List < String >> orders );
// Name maps to total orders made so far
int totalOrders ( Map < String , Integer > orders );
This seems like perfectly legal Java code—but it will not compile. The issue is that
although the two methods seem like normal overloads, after type erasure, the signa‐
ture of both methods becomes:
int totalOrders ( Map );
All that is left after type erasure is the raw type of the container—in this case, Map .
The runtime would be unable to distinguish between the methods by signature, and
so the language specification makes this syntax illegal.
A parameterized type, such as ArrayList<T> , is not instantiable —we cannot create
instances of them. This is because <T> is just a type parameter—merely a place‐
holder for a genuine type. It is only when we provide a concrete value for the type
parameter, (e.g., ArrayList<String> ), that the type becomes fully formed and we
can create objects of that type.
This poses a problem if the type that we want to work with is unknown at compile
time. Fortunately, the Java type system is able to accommodate this concept. It does
so by having an explicit concept of the unknown type —which is represented as <?> .
This is the simplest example of Java's wildcard types .
We can write expressions that involve the unknown type:
ArrayList <?> mysteryList = unknownList ();
Object o = mysteryList . get ( 0 );
This is perfectly valid Java— ArrayList<?> is a complete type that a variable can
have, unlike ArrayList<T> . We don't know anything about the payload type of mys
teryList , but that may not be a problem for our code. When working with the
unknown type, there are some limitations on its use in user code. For example, this
code will not compile:
// Won't compile
mysteryList . add ( new Object ());
Search WWH ::

Custom Search