Java Reference
In-Depth Information
This code works, but is less desirable than the generic version that took
in the array to fill. The main problem is that the above causes an "un-
checked" warning from the compiler. As you may have already noticed,
the cast to E[] is a cast involving a type parameter and such casts have
a different meaning at runtimethe actual cast will be to Object , which is
the erasure of E . Despite this, it is apparent that the code above is type-
safe: We ask for an array that has a component type of E and we try
to use the returned object as such an array. The existence of the "un-
checked" warning is a consequence of a limitation in the Array API and
can't be avoided.
The second problem with the above is that it suffers from the same lim-
itation as the original non-generic version of toArray it will only allow an
array of the exact element type to be created, not an array of any su-
pertype. We can address this latter problem by turning the current ver-
sion into a generic method, as we did previously:
public <T> T[] toArray(Class<T> type) {
int size = size();
T[] arr = (T[]) Array.newInstance(type, size);
int i = 0;
Object[] tmp = arr;
for (Cell<E> c = head;
c != null && i < size;
c = c.getNext())
tmp[i++] = c.getElement();
return arr;
}
This version still has the "unchecked" warningthat can't be avoidedbut
it allows any Class object to passed in and tries to return an array with
that component type. As with the generic version that takes the array as
an argument, this version relies on the runtime checking of array stores
to ensure that the component type passed is actually compatible with
the element type of the current queue.
 
Search WWH ::




Custom Search