ToArray (T []) in ArrayList

When I went through the implementation of ArrayList, I found a strange piece of code in the toArray (T []) method.

public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a 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; } 

Part,

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

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

+6
source share
1 answer

javadoc explains why:

If the list corresponds to the specified array with a spare room (i.e. the array has more elements than the list), the element in the array immediately after 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 null elements.)

+13
source

Source: https://habr.com/ru/post/976148/


All Articles