gpt4 book ai didi

java - 方法更改参数的值

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

方法(Mover)属于 Estado 类,它描述了带有矩阵 tablero(board)和跟踪空位置的变量 Hueco(hole)的滑动拼图的状态。问题是该函数改变了原始 Estado 的值,这是不应该的。有人可以告诉我我做错了什么吗?

public class Estado {
public int dim;
public int tablero[][];
public int hueco[]= new int[2];
public Estado(int dim,int tablero[][],hueco){
this.dim=dim;
this.tablero=tablero;
this.hueco=hueco;

}
public Estado(){}

//moves empty tile to one of 4 option(up,down,right,left)
(up,down,right,left)
//
public Estado mover(String direccion,Estado estado){
Estado sig= new Estado();
sig.tablero=estado.tablero;
sig.dim=estado.dim;
sig.hueco=estado.hueco;
estado.mostrarTablero();
switch (direccion){
case "up":
sig.tablero[estado.hueco[0]][estado.hueco[1]]=sig.tablero[estado.hueco[0]+1][estado.hueco[1]];
sig.tablero[estado.hueco[0]+1][estado.hueco[1]]=0;
sig.hueco[0]=estado.hueco[0]+1;
break;
default:
//cases "down,right and left" omitted, very similar to "up"
break;
}
return sig;

}
}

最佳答案

问题是变量sig指向参数estado的相同数组tablerohueco,因为本声明的内容:

sig.tablero=estado.tablero;
sig.hueco=estado.hueco;

当您调用 mover 方法时,Java 会传递“指针”的副本,但不会传递数组结构的平面副本 (copia plana)。

也许您更喜欢了解按值传递按引用传递主题以及制作平面副本的含义。

编辑:我取自 Programmers StackExchange这应该可以帮助您理解:

Java is pass by value. Think of it like a pointer language like C, the value of the pointer (memory address) is being passed, so you have a reference to the same object. Primitives aren't stored internally the same way as Objects, so when you pass a primitive's value, it's the content, not a pointer.

关于java - 方法更改参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191353/

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