Java Reference
In-Depth Information
Two places where you would usually use a class name but cannot use
a type parameter are when creating objects and arrays. For example,
here is the wrong way to try to expose the elements of a queue as an
array:
class SingleLinkQueue<E> {
// ...
public E[] toArray() {
int size = 0;
for (Cell<E> c = head; c != null; c = c.getNext())
size++;
E[] arr = new E[size]; // INVALID: won't compile
// ... copy in elements ...
}
}
You cannot instantiate E or create an array of E for the same reason you
can't have a static field of type E : There is a single class with a single
definition of toArray , and the compiler has to know at compile time what
code to generate to create any objects or arrays. There is no way for
the compiler to generate newString[size] or newInteger[size] depending
on what E happens to be. [1]
[1] This is a consequence of there being no parameterized type information within objects at runtime-
see Section 11.5 on page 267 .
By now you may be wondering how it is that the compiler can do any-
thing with type parameters? The answer to that is deceptively simple:
The compiler uses the most general possible type to represent the type
parameter (often Object ) and uses type casting to ensure type correct-
ness. You can think of generics as a (potentially optimized) shorthand
for writing all those casts. This is explained in more detail a little later.
So how do you expose the elements of the queue as an array? You could
expose the size of the queue and have the caller create, and pass to
 
 
Search WWH ::




Custom Search