I am having problems understanding how deep copying works. I have this 3d vector that I wish to copy.
int bands[][][] = new int[parameters.numberPredictionBands + 1][][];
int copy[][][] = new int [parameters.numberPredictionBands + 1][][];
Then I pass this vector to some method that changes bands
prepareBands(bands);
And finally I need to create a deep copy of bands, so when copy is changed bands remains the same and viceversa.
copy = copyOf3Dim(bands, copy);
I’ve tried these different methods but they don’t seem to work for me
Method 1:
private int[][][] copyOf3Dim(int[][][] array, int[][][]copy) {
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[0].length; y++) {
for (int z = 0; z < array[0][0].length; z++) {
copy[x][y][z] = array[x][y][z];
}
}
}
return copy;
}
Method 2:
private int[][][] copyOf3Dim(int[][][] array, int[][][]copy) {
for (int i = 0; i < array.length; i++) {
copy[i] = new int[array[i].length][];
for (int j = 0; j < array[i].length; j++) {
copy[i][j] = Arrays.copyOf(array[i][j], array[i][j].length);
}
}
return copy;
}
Method 3:
public int[][][] copyOf3Dim(int[][][] array, int[][][] copy) {
for (int i = 0; i < array.length; i++) {
copy[i] = new int[array[i].length][];
for (int j = 0; j < array[i].length; j++) {
copy[i][j] = new int[array[i][j].length];
System.arraycopy(array[i][j], 0, copy[i][j], 0, array[i][j].length);
}
}
return copy;
}
I think my program crashes when doing array[i].length
Could you please tell me what may I be doing wrong?
A general trick for deep cloning I have successfully used several times is to serialize the object into a
ByteArrayOutputStreamand then immedieately deserialize it. It’s not a top performer, but it’s a simple two-three lines of code and works to any depth.Arrays happen to be
Serializable.