List list = List.of(12, 34, 56);
Integer[] array = list.toArray(new Integer[]{1, 2, 1, 43, 32, 1});
System.out.println(Arrays.toString(array));
输出:` [12, 34, 56, null, 32, 1]`
* * *
不应该是: `[12, 34, 56, null, null, null]` 吗?
这是为什么?
版本:`GraalVM for JDK 17`
看一下toArray方法的源码文档:
* 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,
如果调用者知道列表不包含任何null元素的情况下,方便推断得出列表的真实长度
以ArrayList为例,它的实现如下:
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
if (a.length size)//如果数组的长度大于列表,把列表后面的第一个位置置为null
a[size] = null;
return a;
}
你题目里这个of生成的应该是一个UnmodifiableList? 它的实现也差不多,总之也是只把紧跟着列表后面的那个元素置为null:
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
// We don't pass a to c.toArray, to avoid window of
// vulnerability wherein an unscrupulous multithreaded client
// could get his hands on raw (unwrapped) Entries from c.
Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
for (int i=0; i((Map.Entry)arr[i]);
if (arr.length > a.length)
return (T[])arr;
System.arraycopy(arr, 0, a, 0, arr.length);
if (a.length > arr.length)
a[arr.length] = null;//看这里看这里
return a;
}