过去4天我的Java代码存在问题,在我的生活中,我找不到它的根本原因。
基本上,我创建了一个对象列表的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时,列表中的所有模型也会被更改!
答案 0 :(得分:2)
您必须clone
2-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;
}
答案 1 :(得分:0)
非常感谢,问题确实在于深层复制:
公共类Matrix { public 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))));