使用循环将多个对象添加到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, 

任何帮助或建议都将不胜感激,因为我已经试图找到一个解决方案一个多星期了,这让我发疯了。

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

最新更新