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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...