prasanth
prasanth

Reputation: 3602

toArray(T[]) method in ArrayList

When I was going through ArrayList implementation, I found a weird piece of code in toArray(T[]) method.

 public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

The part is,

 if (a.length > size)
    a[size] = null;

why only the element at this index in the array is set to null? Once the array is filled with the contents of the list, the elements at the remaining indices should have been set to null, right? Or am I missing something here?

Upvotes: 6

Views: 275

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120516

The javadoc explains why:

If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the list is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

Upvotes: 14

Related Questions