【问题标题】:Adding multiple objects to ArrayList using loop, all objects get updated when one is changed使用循环将多个对象添加到 ArrayList,当一个对象更改时,所有对象都会更新
【发布时间】:2020-12-02 05:27:23
【问题描述】:

我一直在使用 for 循环创建新的 Graph 对象并将其添加到 ArrayList 以在我的代码中的其他地方使用,但是当我打印列表时,里面的所有 Graph 对象都是相同的。

对其中一个对象的编辑将在其余部分进行。当我使用调试器检查发生了什么时,每个 newGraph 都有不同的 ID,所以我不知道为什么会发生这种情况。代码如下。我已经包含了足够多的内容,所以它是可测试的。

public class Graph {
    int[][] A;
    public static final int graphSize = 5;
  
    public Graph() {
        A = new int[graphSize][graphSize];
    }
    public Graph(Graph another) {
        this.A = another.A;
    }

//This is where the problem is, everything else is so it would run if tested.
    public List<Graph> getAllPossibleGraphs(int playerTurn) {
        List<Graph> possibleGraphs = new ArrayList<>();
        for (int i = 0; i < graphSize; i++) {
            for (int j = 0; j < graphSize; j ++) {
                if (i != j && 0 == this.A[i][j]) {
                    Graph newGraph = new Graph(this);
                    newGraph.insertLine(i, j, playerTurn);
                    possibleGraphs.add(newGraph);
                }
            }
        }
        return possibleGraphs;
    }

    public void insertLine(int node1, int node2, int player) {
            this.A[node1][node2] = player;
            this.A[node2][node1] = player;
    }
    public void printGraph() {
        for (int i = 0; i < Graph.graphSize; i++) {
            for (int j = 0; j < Graph.graphSize; j++) {
                System.out.print(this.A[i][j] + ", ");
            }
            System.out.println("");
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Graph G = new Graph();
        G.insertLine(0, 1, 1);
        List<Graph> testList = G.getAllPossibleGraphs(2);
        testList.forEach(graph -> graph.printGraph());
    }
}

所以当我打印出列表时,我得到的所有图表如下:

0, 1, 2, 2, 2, 
1, 0, 2, 2, 2, 
2, 2, 0, 2, 2, 
2, 2, 2, 0, 2, 
2, 2, 2, 2, 0, 

任何帮助或建议都将不胜感激,因为我一个多星期以来一直在努力解决这个问题,这让我发疯了。

【问题讨论】:

  • 需要查看正在使用的 Graph 的构造函数。如果对一个对象的修改也发生在其他对象上,那么听起来所有变量都指向同一个引用。
  • 感谢您的评论,我已将构造函数添加到上述信息中。对于任何反馈,我们都表示感谢。再次感谢您抽出宝贵时间查看和评论。
  • 请提供minimal reproducible example,很可能您使用的是静态字段而不是实例字段。
  • 谢谢,我已经添加了更多内容,以便人们可以测试它,但它似乎相当长,所以我不知道这是否可以 - 仍然是新手。

标签: java for-loop object arraylist


【解决方案1】:

您正在共享 A,但可能需要一份副本。诚然,我不明白其中的逻辑(太热了)。

public Graph(Graph another) {
    this();
    for (int i = 0; i < Graph.graphSize; i++) {
        for (int j = 0; j < Graph.graphSize; j++) {
            A[i][j] = another.A[i][j];
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多