为什么 Java 在使用 List.toArray 时向数组插入空值

Why Java inserts null to array when using List.toArray

代码片段的输出

List<Integer> list = List.of(10, 20, 30, 40, 50);
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
list.toArray(array);
System.out.println(Arrays.toString(array));

是:

[10, 20, 30, 40, 50, null, 7, 8, 9, 0]

我在 ArrayList.toArray 方法中找到了以下代码:

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

这种行为的原因是什么? 为什么 may 示例中的第 5 个元素是 null,而不是 6

此类行为记录在 List::toArray(T[]) 的 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.)

(强调我的。)

我觉得有点 相当 非常很难想出一个具体的例子, 但至少 null 元素的位置等于调用 toArray.

之前列表的原始长度