我的代码应该可以很好地解释我的情况。如果没有,那么;我调用这个方法,它返回“错误”的值。不知何故,它要么改变一个数组列表的值,要么将它们设置为相等。我做错了什么?
public ArrayList<Piece> bestMove (ArrayList<Piece> b, int index) {
System.out.println ("possible moves = " +this.getPossibleMoves(b, index)); // prints 2
if (this.getPossibleMoves(b, index) > 0) { // the problem isn't here
// is the problem here?
ArrayList<Piece> cloneAlpha = (ArrayList<Piece>) b.clone();
ArrayList<Piece> cloneBeta = (ArrayList<Piece>) b.clone();
int x = b.get(index).x; // x = 4
int y = b.get(index).y; // y = 3
// x + 1 = 5
// y + 1 = 4
if (!this.checkSquare(x+1, x+1, cloneAlpha)) {
cloneAlpha.get(index).setXY((x+1), (x+1));
System.out.println (cloneAlpha.get(index).x + ", " + cloneAlpha.get(index).y); // prints "5, 4"
}
// Something goes on between these two conditions
// it can't be checkSquare method
// nor the setXY
// x - 1 = 3
// y + 1 = 4
if (!this.checkSquare(x-1, y+1, cloneBeta)) {
cloneBeta.get(index).setXY(x-1, y+1);
System.out.println (cloneBeta.get(index).x + ", " + cloneBeta.get(index).y); // prints "3, 4"
}
System.out.println (cloneAlpha.get(index).x + ", " + cloneAlpha.get(index).y); // prints "3, 4"
System.out.println (cloneBeta.get(index).x + ", " + cloneBeta.get(index).y); // prints "3, 4"
return cloneAlpha;
}
return b;
}
最佳答案
clone()
仅创建浅拷贝,对于集合而言,这意味着所包含的对象将不会被克隆。如果你想要深度克隆,你必须自己实现。
一个更简单、可能更好的解决方案是完全避免克隆:您可以创建一个新的空集合,迭代原始集合并构建一个新的 Piece,而不是创建原始集合的副本然后修改内容
具有修改值的对象。
然后您甚至可以使 Piece
不可变,这本身通常是一个好主意。
关于 java ;一个数组列表的两个本地克隆是否使它们的值相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9447777/