通过引用传递会毁掉一切:(
嘿人们,我有这个搜索树结构
class State
{
//CLASS STATE
int value;
char[][] state; //the game Grid
State child[]; // children of current state, maximum is 8
State(char[][] src)
{
state=src;
child=new State[8];
}
,这是最大值函数中递归结束后的根节点定义
State rootNode = new State(currentGrid);
rootNode.value=-1;
int v =maxValue(rootNode,depth);
,rootNode 中的数组不应该被编辑,因为它是第一个状态,但是当我显示它时,我得到一个填充的数组这意味着 rootNode.state 通过引用最大值函数传递:(
//我正在尝试实现 MiniMax 算法。
Hey people i have this structure for the search tree
class State
{
//CLASS STATE
int value;
char[][] state; //the game Grid
State child[]; // children of current state, maximum is 8
State(char[][] src)
{
state=src;
child=new State[8];
}
this is the root node definition
State rootNode = new State(currentGrid);
rootNode.value=-1;
int v =maxValue(rootNode,depth);
after the end of recursion in the max value function the array in rootNode should not be edited since its the the first state but when i Display it i get an array filled with stuff which means that the rootNode.state passed by reference to the max value function :(
//i am trying to implement MiniMax Algorithm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不希望更改作为参数传递的对象,请传入一个副本(或在方法内制作参数的副本)。
请注意,
char[][]
意味着您有一个 char 数组的数组,即您正在处理对象,如果您复制第一个级别,您仍然可能拥有对第二个级别的引用。因此,您可能必须循环遍历第一个级别/维度并复制其中的所有数组,如下所示:
If you don't want objects that are passed as parameters to be changed, pass in a copy (or make a copy of the parameter inside the method).
Note that
char[][]
means you have an array of char arrays, i.e. you are working with objects and if you copy the first level you still might have a reference to the second.Thus you might have to loop through the first level/dimension and copy all the arrays in there, like this:
如果需要,您可以通过
Arrays.copyOf
您还可以创建深层副本。如何做到这一点已在这里得到解答:如何深度复制不规则的二维数组
If you need, you can easily create a copy of the array through
Arrays.copyOf
You can also create a deep copy. How to do this has been answered here: How to deep copy an irregular 2D array
是的,Java 传递对数组的引用,而不是将数组作为值传递。因此,如果您给出对内部状态的引用,接收者可以更改它,并且更改在源中“可见”(事实上:只有一个数组已更改,并且所有引用持有者将看到变化)。
快速修复/解决方案:克隆您的状态数组并传递对此克隆的引用而不是原始数组。这将使您的内部根状态保持不变。
Yes, Java passes references to arrays and not the array as a value. So if you give a reference to your internal state away, the receiver can change it and the change is "visible" in the source (in fact: it's only one array that has been changed and all reference holders will see the change).
Quick fix/solution: clone your state array and pass a reference to this clone instead of the original. This will keep your internal root state unmodified.