简体   繁体   English

Java中2D数组的ArrayList

[英]ArrayList of Arrays to 2d Array in Java

I recently had a problem typecasting/converting an ArrayList of arrays to a 2d array. 我最近在将数组的ArrayList转换/转换为2d数组时遇到问题。 I found an answer on this site that told me to use 我在这个网站上找到一个答案,告诉我使用

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

That worked, but I googled it for a bit and read somewhere that it is conseidered bad practice. 那行得通,但我在Google上搜索了一下,并在某处阅读了认为是不良做法的内容。 I still used it, as it was the only one line variant that actually worked. 我仍然使用它,因为它是唯一实际起作用的行变体。

What does it actually mean and why is it considered bad? 它实际上是什么意思,为什么它被认为是不好的? I don't understand the [][]{} bit. 我不明白[][]{}位。 I'm guessing that you pass an empty but initialized Object[][] to the .toArray() method? 我猜想您将一个空的但已初始化的Object[][]传递给.toArray()方法?

我找不到任何理由将您的示例视为不良做法!

The only thing I see is that it creates an array but will not use it. 我唯一看到的是它将创建一个数组,但不会使用它。

One the Javadoc you can see: 您可以看到一个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. 否则,将使用指定数组的运行时类型和此列表的大小分配一个新数组。

And it can be verified on the method source code: 可以在方法源代码上进行验证:

@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;
}

So what you are creating is an empty array, then the method will create another one. 因此,您要创建的是一个空数组,然后该方法将创建另一个数组。

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

Concerning the [][]{} your guess is correct. 关于[][]{}您的猜测是正确的。

Some tips here 这里的一些技巧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM