很难解释我的问题是什么。我想要的只是创建一个重复的对象并操作新对象而不影响原始对象的数据。
假设我有一个 TicTacToe 类,并且创建了 2 个对象,game1 和 testField
TicTacToe game1 = new TicTacToe();
TicTacToe testField = new TicTacToe();
该类具有多个属性,但这是在本例中受影响的属性
String[] gameField[9];
我想要做的就是使用新初始化的对象进入 for 循环,将其“gameField”设置为对象“game1”的“gameField”。不要介意发生的所有废话...此外,在每次循环之后,它都会重置回“game1”对象
TicTacToe testField = new TicTacToe();
for (int i = 0; i < 9; i++)
{
testField.gameField = game1.gameField;
q = i+1;
if (testField.gameField[i].equals("" + q))
{
if (testField.humanStart) testField.gameField[i] = "O";
else testField.gameField[i] = "X";
game1.printField();
testField.printField();
if (testField.checkWin() == 2)
{
bestMove = "" + q;
break;
}
}
}
这里的问题是两个对象都受到影响,即使它应该被重置。
抱歉,如果我说得不够清楚。 谢谢您的帮助。
最佳答案
问题出在行 testField.gameField = game1.gameField;
我认为你想做的是:
System.arraycopy( testField.gameField, 0, game1.gameField, 0, testField.gameField.length );
或者,你可以这样做:
testField.gameField = game1.gameField.clone();
关于java - 如何创建一个对象,将其设置为与另一个对象完全相同,并修改它而不影响循环内的旧对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35355670/