How can I deep copy an irregularly shaped 2D array in Java?
Ie.
int[][] nums = {{5},
{9,4},
{1,7,8},
N-dimensional deep copy
public class ArrayTest extends TestCase {
public void testArrays() {
Object arr = new int[][]{
{5},
{9, 4},
{1, 7, 8},
{8, 3, 2, 10}
};
Object arrCopy = copyNd(arr);
int height = Array.getLength(arr);
for (int r = 0; r < height; r++) {
Object rowOrigonal = Array.get(arr, r);
Object rowCopy = Array.get(arrCopy, r);
int width = Array.getLength(rowOrigonal);
for (int c = 0; c < width; c++) {
assertTrue(rowOrigonal.getClass().isArray());
assertTrue(rowCopy.getClass().isArray());
assertEquals(Array.get(rowOrigonal, c), Array.get(rowCopy, c));
System.out.println(Array.get(rowOrigonal, c) + ":" + Array.get(rowCopy, c));
}
}
}
public static Object copyNd(Object arr) {
if (arr.getClass().isArray()) {
int innerArrayLength = Array.getLength(arr);
Class component = arr.getClass().getComponentType();
Object newInnerArray = Array.newInstance(component, innerArrayLength);
//copy each elem of the array
for (int i = 0; i < innerArrayLength; i++) {
Object elem = copyNd(Array.get(arr, i));
Array.set(newInnerArray, i, elem);
}
return newInnerArray;
} else {
return arr;//cant deep copy an opac object??
}
}
}