微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/java/127198.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐