java list.toArray 方法?

作者站长头像
站长
· 阅读数 6
        List<Integer> 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

回复
1个回答
avatar
test
2024-06-26

看一下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 <tt>null</tt>.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any null elements.)

意思就是如果数组的元素比列表多,数组中紧跟在列表末尾后面那一位置的元素设置为null,如果调用者知道列表不包含任何null元素的情况下,方便推断得出列表的真实长度以ArrayList为例,它的实现如下:

@SuppressWarnings("unchecked")
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);
    if (a.length > size)//如果数组的长度大于列表,把列表后面的第一个位置置为null
        a[size] = null;
    return a;
}

你题目里这个of生成的应该是一个UnmodifiableList? 它的实现也差不多,总之也是只把紧跟着列表后面的那个元素置为null:

@SuppressWarnings("unchecked")
public <T> 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<arr.length; i++)
        arr[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)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;
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容