简体   繁体   English

将复制任何多维数组的通用函数

[英]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. 我将通过它的类型最有可能是用户定义的,例如我有一个我希望以这种方式使用的Tile类。

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就会抛出此异常:

java.lang.ClassCastException: [[Ljava.lang.Object; java.lang.ClassCastException:[[Ljava.lang.Object; cannot be cast to [[Lboard.Tile; 不能投[[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() 这是我基于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[][] . 发生异常,因为毕竟数组仍然是Object[][]类型,而不是类型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});

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

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