我正在使用数组列表来添加状态(8 个拼图的棋盘状态)。我的问题是,当我获取状态的子级时,它会更改存储在数组列表中的值。我假设这是因为 ArrayList 仅存储指向对象的指针而不是值本身。为了解决这个问题,我每次将其存储到 ArrayList 之前都会创建一个新对象,但我仍然遇到同样的问题。
我也会尝试更多地遵循命名约定,感谢您的提示。
private ArrayList<int[][]>VisitedBoard;
if(RuleNumber ==2){
//Here is my problem. This will change what is stored in VistedBoards
NextState = new State(FireRule.Rule2(WM.get_Board()));//Fire Rule
for(int j=0;j<VisitedBoards.size();j++){
//Meaning this will always be true
if(Arrays.equals(VisitedBoards.get(j), NextState.get_Board())){
Loop =true; //Loop to previous state
}
if(j==VisitedBoards.size()-1 && Loop ==false){ //If the next state is not any previously visited
NotALoop =true;
VisitedBoards.add(NextState.get_Board());
WM.set_Board(NextState.get_Board());
}
}
}
public int[][] Rule2(int [][] Board){//The FireRule Class
Find_BlankLocation(Board);
int temp;
State NewState;
temp = Board[BlankLocation[0]-1][BlankLocation[1]];
Board[BlankLocation[0]-1][BlankLocation[1]] = 0;
Board[BlankLocation[0]][BlankLocation[1]] = temp;
NewState = new State(Board);
return Board;
}
public class State { //State class
private int[][] Board;
private int[][] Goal;
private Boolean GoalFound;
public State(int[][] Start, int[][] goal){
Board = Start;
Goal = goal;
GoalFound=false;
}
public State(int[][] NewState){
Board=NewState;
}
public int[][] get_Goal(){
return Goal;
}
public int[][] get_Board(){
return Board;
}
public void set_Board(int[][] board){
Board = board;
}
public Boolean get_GoalFound(){
return GoalFound;
}
}
最佳答案
像ArrayList
这样的容器在所有语言中的工作方式都是相同的:它们被称为数据结构,因为它们组织对象的存储/检索。显然它们不存储对象本身的字段。
尝试解释您的问题,也许您不想在 visitedBoards
列表和 WM
列表之间共享图板(无论这意味着什么......)。然后只需实现 get_Board()
即可返回数组的副本,而不是 Board
对象本身:
public int[][] get_Board(int[][] src) {
int[][] dst = new int[src.length][src[0].length];
for (int i = 0; i < src.length; i++) {
System.arraycopy(src[i], 0, dst[i], 0, src[i].length);
}
return dst;return dst;
}
除此之外,正如其他人已经告诉您的那样,您最好采用标准 Java 命名约定,使用有意义的名称,并封装您的 x
、y
和实际应用程序类中的int[][]
。
关于java - 处理 ArrayList 并按引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15580493/