加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:56:33 所属栏目:Java 来源:网络整理
导读:当我通过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()); Syste
当我通过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.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读