Java Reference
In-Depth Information
11.3. Generic Methods and Constructors
Earlier we mentioned how the SingleLinkQueue class might want to expose
the elements of the queue as an array. We noted then that it was im-
possible to create an array with the type variable E and that instead the
caller should pass in an array of the right size and type. Here's a first
attempt at defining such a method:
public E[] toArray_v1(E[] arr) { // too restrictive!
int i = 0;
for (Cell<E> c = head;
c != null && i < arr.length;
c = c.getNext())
arr[i++] = c.getElement();
return arr;
}
This method works. If you invoke toArray_v1 on an instance of
SingleLinkQueue<String> and pass a String[] , then as many elements from
the queue as the array can hold will be copied into it, and then the ar-
ray will be returned. The problem with this definition, as you may have
already surmised from the discussion of wildcards, is that it is too re-
strictive. It will, in the current example, accept only a String[] and not,
for example, an Object[] even though it is perfectly valid to store String
objects into an Object[] .
Can we use a wildcard to help us out in this situation as well? Unfortu-
nately not. To use a wildcard we'd try writing something like this:
public ?[] toArray(?[]) { ... } // INVALID: won't compile
But this is simply not legal syntax: A wildcard represents an unknown
type in a parameterized type definition and ' ?[] ' is not a parameterized
type. What you need to do is introduce another type variable, say T , and
 
Search WWH ::




Custom Search