2013-02-20 83 views
1

我在理解深度複製的工作原理時遇到問題。我有這個我想複製的3d矢量。深度複製3維陣列

int bands[][][] = new int[parameters.numberPredictionBands + 1][][]; 
int copy[][][] = new int [parameters.numberPredictionBands + 1][][]; 

然後,我通過這個載體來一些改變帶

prepareBands(bands); 

最後,我需要創建樂隊的深層副本方法,所以當拷貝改變帶保持不變,反之亦然。

copy = copyOf3Dim(bands, copy); 

我已經嘗試了這些不同的方法,但他們似乎並沒有爲我

方法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; 
} 

方法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; 
} 

方法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; 
}  

我認爲我的程序在做的時候崩潰了array[i].length

請問我可能做錯了什麼?

+3

當數組[i]爲空時,即沒有子數組時,它崩潰。 – Ingo 2013-02-20 21:01:54

回答

3

深度克隆的一般技巧我已經成功地使用了幾次,將對象序列化爲ByteArrayOutputStream,然後立即反序列化它。這不是一個優秀的表演者,但它是一個簡單的兩三行代碼,可以在任何深度工作。

陣列碰巧是Serializable

final ByteArrayOutputStream out = new ByteArrayOutputStream(); 
new ObjectOutputStream(out).writeObject(array); 
final Spec clone = (int[][][]) 
    new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())). 
+0

你能提供一個例子嗎?我不太明白 – strv7 2013-02-21 09:19:13