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?
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
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.
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.
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 anynull
elements.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With