首页 > 解决方案 > 使用循环将多个对象添加到 ArrayList,当一个对象更改时,所有对象都会更新

问题描述

我一直在使用 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, 

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

标签: javafor-loopobjectarraylist

解决方案


您正在共享 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];
        }
    }
}

推荐阅读