简体   繁体   中英

Generic function which will copy any multidimensional array

Like the title says I'm trying to create a copy of a multidimensional array, 2 dimensional array to be exact, in a generic way so I can reuse this else where.

The types I will be passing it most likely will be all user defined, for example I have a Tile class that I wish to utilize in this way.

My current problem is the code below:

While in the debugger you can follow the calls and see that the elements in the arrays are being assigned correctly but as soon as the result is returned java throws this exception:

java.lang.ClassCastException: [[Ljava.lang.Object; cannot be cast to [[Lboard.Tile;

@SuppressWarnings("unchecked")
public static <T> T[][] clone(T[][] source) {
    T[][] result = (T[][]) new Object[source.length][source[0].length];
    for (int row = 0; row < source.length; row++) {
        result[row] = Arrays.copyOf(source[row], source[0].length);
    }
    return result;
}

Anyone know of a good way to do this? Optimization is not an issue.

Thanks

Here is my approach based on Array.copyOf()

static <T> T[][] clone(T[][] source) {
    Class<? extends T[][]> type = (Class<? extends T[][]>) source.getClass();
    T[][] copy = (T[][]) Array.newInstance(type.getComponentType(), source.length);

    Class<? extends T[]> itemType = (Class<? extends T[]>) source[0].getClass();
    for (int i = 0; i < source.length; i++) {
        copy[i] = (T[]) Array.newInstance(itemType.getComponentType(), source[i].length);
        System.arraycopy(source[i], 0, copy[i], 0, source[i].length);
    }
    return copy;
}

The trick is to obtain the type of the items and create arrays by explicitly specifying this type.

EDIT: don't forget to check if source is null :)

The exception occurs, because after all the array is still of type Object[][] not of type T[][] . You can work around this by using reflection, like this (but it's nasty):

T[][] result = (T[][]) java.lang.reflect.Array.newInstance(source[0][0].getClass(), new int[]{source.length, source[0].length});

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