2017-09-15 44 views
-1

我的Java代碼在過去的4天中遇到了問題,在我的生活中,我無法找到它的根本原因。在ArrayList中存儲值而不是引用

基本上,我創建一個對象列表的ArrayList,其中有一個對象列表作爲屬性。但是,當我嘗試在列表的第一個元素中應用方法時,其他對象也會更新!

這裏是我的對象結構的基本概述:

public class Matrix { 
    public double[][] A; 

    public Matrix(double[][] A) { 
     this.A = A; 
    } 
} 
public class Model { 
    public Matrix M; 

    public Model(Matrix M) { 
     this.M = M; 
    } 

    public static Model(Model m) { 
     // modifying model a bit 
     return newModel; 
    } 
} 

public class MyProgram { 
    public ArrayList<Model> models; 

    public main() { 
     this.models = new ArrayList<Model>(NUM); 
     Matrix A = randomMatrix(); 
     for (int i = 0; i < NUM; i++) { 
      this.models.add(new Model(A)); 
     } 
    } 

    public otherMethod() { 
     this.models.set(0, changeModel(this.models.get(0))); 
    } 
} 

的問題是每當我調用otherMethod,列表中的所有模型會改變的!

+1

什麼錯在何處?你沒有描述任何特定的問題/輸出問題? –

+0

Java的操作與您所說的完全相同。你說你的所有模型都應該有相同的'Matrix'(假設這就是關於循環隱藏的評論)。所以當你在一個Model中改變Matrix時,你也改變了所有其他模型中的Matrix。 –

+0

@TheophileDano我更新瓦特/問題:) – Mehdi

回答

2

你必須clone2-D array不只是爲它分配:

所以不是this.A = A;

你應該使用這樣的複製:

public static int[][] deepCopyIntMatrix(int[][] input) { 
    if (input == null) 
     return null; 

    int[][] result = new int[input.length][]; 

    for (int r = 0; r < input.length; r++) { 
     result[r] = input[r].clone(); 
    } 
    return result; 
} 
+2

或使用'System.arrayCopy' –

0

非常感謝,這個問題確實關於深拷貝:

公開課Matrix:{ publ ic double [] [] A;

public Matrix(double[][] A) { 
    A = new double[n][m]; 
    for(int i=...) 
     for(int j=...) 
       this.A[i][j] = A[i][j]; 
} 

,並增加我的矩陣,我這樣做:

this.models.add(new Model(new Matrix(A.A)))); 
+0

編號請,這是不準確的。我之所以失去了最後三天的工作。克隆方法顯然只適用於一維數組。 – Mehdi