关于ArrayList toArray的疑问 (if (a.length > size)a[size] = null;)

import java.util.ArrayList;

import java.util.List;

public class Test {

public static void main(String[] args) {

List<Integer> integerList = new ArrayList<>();

integerList.add(11);

integerList.add(22);

integerList.add(33);

integerList.add(44);

integerList.add(55);

Integer[] a1 = {1, 2, 3, 4, 5, 6, 7, 8};

Integer[] integers = integerList.toArray(a1);

for (Integer integer : integers) {

System.out.println(integer);

}

}

}

输出了
11
22
33
44
55
null
7
8

jdk1.8 ArrayList toArray 源码 想不通的问题在下面注释里面。

    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, 0, a, 0, size);

//**我想不通的是,这一行的作用是为什么? 如果大于则置空第size的元素,是提醒调用者,俩个数组的长度必须一致吗?**

if (a.length > size)

a[size] = null;

return a;

}

回答

JDK 里是怎么描述的:

https://docs.oracle.com/javas...:A-

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

最后的括号里就是所谓的“原因”,翻译成中文大致就是:“只有当调用者知道列表不包含任何空元素时,才有助于确定列表的长度。”

但你要问这是为什么,我特么也不知道,我就觉得这设计挺傻缺的。

可能是一种古老的习惯,用一个特殊值表示内容结束,比如在 char[] 里用 0 表示内容结束,在int[]里用 -1 表示内容结束…
以及,除非有现成的数组,否则这个方法的正确用法是传一个长度0的数组(相当于只传类型)

说不定是为了标识,哈哈

以前,我在回答另一个问题Java 集合转数组问题, list.toArray(T[] a)的时候,由于这个是问题也是关于toArray的方法的,不过当时问的和你问的不一样,但是我却在回答这个问题的时候,发现了和你一样的疑问
image.png

最后看没人讨论,我就去stackoverflow上问了一把(stackoverflow问题链接

真有个大佬给我解释了一下
image.png

大致意思就是设计者参考以前C语言的处理怪癖注意,这里用到了一个词语quirk,大佬也最后吐槽说如果要是这种设计发生在现在会发什么反应。。。

以上是 关于ArrayList toArray的疑问 (if (a.length &gt; size)a[size] = null;) 的全部内容, 来源链接: utcz.com/a/29178.html

回到顶部