java - Generic function which will copy any multidimensional array -


like title says i'm trying create copy of multidimensional array, 2 dimensional array exact, in generic way can reuse else where.

the types passing user defined, example have tile class wish utilize in way.

my current problem code below:

while in debugger can follow calls , see elements in arrays being assigned correctly result returned java throws exception:

java.lang.classcastexception: [[ljava.lang.object; cannot cast [[lboard.tile;

@suppresswarnings("unchecked") public static <t> t[][] clone(t[][] source) {     t[][] result = (t[][]) new object[source.length][source[0].length];     (int row = 0; row < source.length; row++) {         result[row] = arrays.copyof(source[row], source[0].length);     }     return result; } 

anyone know of way this? optimization not issue.

thanks

the exception occurs, because after array still of type object[][] not of type t[][]. can work around using reflection, (but it's nasty):

t[][] result = (t[][]) java.lang.reflect.array.newinstance(source[0][0].getclass(), new int[]{source.length, source[0].length}); 

Comments