gpt4 book ai didi

java - 复制 Java 变量

转载 作者:行者123 更新时间:2023-12-01 11:49:31 26 4
gpt4 key购买 nike

我的程序中有以下内容:

 public static GameBoard possibleStates(GameBoard GameState, int turn)
{
printGameBoard(GameState); //getting what is passed in here
int innerCounter = 0;
int outerCounter = 0;
while(outerCounter < 3)
{
while(innerCounter < 3)
{
if(GameState.Board[outerCounter][innerCounter].isEmpty())
{
GameBoard PossibleBoard = new GameBoard();
PossibleBoard.Copy(GameState);
PossibleBoard.Board[outerCounter][innerCounter].ModifyOccupy(move); //the problem is here, changes to possibleboard are also reflected in gamestate
GameState.AddToActions(PossibleBoard);
}
innerCounter++;
}
innerCounter = 0;
outerCounter++;
}
return GameState;
}

我的问题是,改变一个,就会改变另一个的值(value)。我知道这是因为他们引用了内存中的相同空间,我只是不知道如何不让他们这样做。我已经尝试过对我的 GameBoard 类使用 Copy 方法和 Clone 方法,但它们没有产生任何区别。

最佳答案

在实际创建副本的复制方法中,您需要创建深拷贝。也就是说,复制引用是不够的,您需要创建新对象并使用原始对象的状态初始化它们。

只有这样,它才是一个完全独立的对象,不会改变原来的对象。

这可能是一个有用的细节

What is the difference between a deep copy and a shallow copy?

关于java - 复制 Java 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com