I have tried everything I can think of and have searched for it everywhere online, but I can't get it to work. Below I have two Java methods, the first one I successfully got to work, and the other I can't make work. The first method, printArray(), accepts any array, regardless of object type and number of dimensions, and prints the results to the screen. The method does this recursively, meaning it calls itself within itself and loops through each dimension that way.
For the second method, deepClone(), I need it to accept any array as well, and return a deep copy. The way it's set up, I can make a clone of the leftmost dimension, but not of other dimensions. Every dimension within the cloned array needs to reference its own place in memory. Wherever I put the recursion (the deepClone() method call), the function seems to either not change in the way it acts, or give a StackOverflowError. I have also tried putting the recursion in the set method and the return statement.
Any help is greatly appreciated. I have to do this using reflection, and the method has to be static. The recursion is optional. Any proposed way of achieving this, either recursively or through another way, is greatly appreciated.
public static void printArray(Object array) { // This method works fine
if (array.getClass().isArray())
for (int i = 0; i < Array.getLength(array); i++) {
printArray(Array.get(array, i));
System.out.println();
}
else
System.out.print("{" + array + "} ");
}
public static Object deepClone(Object array) { // This method does not work properly
Class c = array.getClass().getComponentType();
Object newArray = new Object();
if (c.isArray()) {
newArray = Array.newInstance(c, Array.getLength(array));
for (int i = 0; i < Array.getLength(newArray); i++) {
deepClone(Array.get(array, i));
Array.set(newArray, i, Array.get(array, i));
}
}
return newArray;
}
Thank you.