【问题标题】:Storing values instead of references in ArrayList在 ArrayList 中存储值而不是引用
【发布时间】:2017-09-15 15:06:28
【问题描述】:

在过去的 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 时,列表中的所有模型也会更改!

【问题讨论】:

  • 出了什么问题?你没有描述任何特定的问题/输出问题?
  • Java 完全按照你说的做。你说你所有的模型都应该有相同的Matrix(假设这就是关于循环隐藏的评论)。因此,当您将Matrix 更改为一个Model 时,您也会更改所有其他模型中的相同Matrix
  • @TheophileDano 我更新了这个问题:)

标签: java pointers memory jvm


【解决方案1】:

你必须 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;
}

【讨论】:

  • 或使用System.arrayCopy
【解决方案2】:

非常感谢,问题确实是关于深拷贝:

公共类矩阵{ 公共双[][] 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))));

【讨论】:

  • 没有。拜托,这是不准确的。以及我失去最后三天工作的原因。克隆方法显然只适用于一维数组。
猜你喜欢
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 2012-03-31
  • 2013-10-25
  • 2017-11-23
相关资源
最近更新 更多