gpt4 book ai didi

java - Java 中数组的 ArrayList 到 2d 数组

转载 作者:行者123 更新时间:2023-11-30 02:48:29 25 4
gpt4 key购买 nike

我最近在将数组的 ArrayList 类型转换/转换为二维数组时遇到问题。我在这个网站上找到了一个答案,告诉我使用

List<Object[]> arrayList;
// initialize and fill the list of arrays
// all arrays have the same length
Object[][] array2d = arrayList.toArray(new Object[][] {});

这确实有效,但我在谷歌上搜索了一下,并在某处读到这被认为是不好的做法。我仍然使用它,因为它是唯一真正有效的单行变体。

它的实际含义是什么?为什么它被认为是不好的?我不明白 [][]{} 位。我猜您将一个空但已初始化的 Object[][] 传递给 .toArray() 方法?

最佳答案

我唯一看到的是它创建了一个数组但不会使用它。

您可以看到的 Javadoc:

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

并且可以在方法源码上验证:

@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)
a[size] = null;
return a;
}

因此,您创建的是一个空数组,然后该方法将创建另一个空数组。

Object[][] array2d = arrayList.toArray(new Object[arrayList.size()][]);

关于[][]{},您的猜测是正确的。

一些提示 here

关于java - Java 中数组的 ArrayList 到 2d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39429225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com