简体   繁体   中英

ArrayList of Arrays to 2d Array in Java

I recently had a problem typecasting/converting an ArrayList of arrays to a 2d array. 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. 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?

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

The only thing I see is that it creates an array but will not use it.

One the Javadoc you can see:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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