Java – toArray (t []) method in ArrayList
•
Java
When I implemented it through 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's runtime type,but my contents: return (T[]) Arrays.copyOf(elementData,size,a.getClass()); System.arraycopy(elementData,a,size); if (a.length > size) a[size] = null; return a; }
This part is,
if (a.length > size) a[size] = null;
Why is only the element at this index in the array set to null? Once the array fills the contents of the list, the elements at the remaining indexes should be set to null, right? Or what am I missing here?
Solution
Javadoc explains why:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码