ArrayList中的java – toArray(T [])方法

前端之家收集整理的这篇文章主要介绍了ArrayList中的java – toArray(T [])方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我通过ArrayList实现时,我在toArray(T [])方法中发现了一段奇怪的代码.
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;
    }

这部分是,

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

为什么只有数组中此索引处的元素设置为null?一旦数组填充了列表的内容,其余索引处的元素应该设置为null,对吧?或者我在这里遗漏了什么?

解决方法

javadoc解释了原因:

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

猜你在找的Java相关文章