Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toArray(T[]) method in ArrayList

Tags:

java

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?

like image 990
prasanth Avatar asked Oct 02 '14 13:10

prasanth


People also ask

What is the use of toArray () in Java?

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

What does the toArray () method do when called on a list?

toArray. Returns an array containing all of the elements in this list in proper sequence (from first to last element). The returned array will be "safe" in that no references to it are maintained by this list.

What is toArray method?

The Java ArrayList toArray() method converts an arraylist into an array and returns it. The syntax of the toArray() method is: arraylist.toArray(T[] arr) Here, arraylist is an object of the ArrayList class.


1 Answers

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.)

like image 180
Mike Samuel Avatar answered Oct 12 '22 09:10

Mike Samuel