我使用arraylist添加狀態(8拼圖板狀態)。我的問題是當我得到狀態的孩子時,它改變了存儲在我的數組列表中的值。我假設這是因爲ArrayList只存儲指向對象的指針而不是值本身。爲了解決這個問題,我在每次將它存儲到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;
}
}
由於您不遵循命名約定,因此很難遵循您的代碼。類名應該大寫,變量名應該是小寫。 Java中不使用下劃線(通常)。當你習慣使用不遵循這些約定的代碼時,你會感到驚訝。 – jahroy 2013-03-22 22:01:46
請顯示「NextState」類的代碼。我們需要看看'get_Board()'方法真的知道發生了什麼。 – jahroy 2013-03-22 22:03:24
我甚至都不明白你在問什麼。請檢查你的問題,並明確指出你看到的結果和預期的結果。可能,發佈一個簡明的代碼示例,顯示您的問題,並可以運行 – Raffaele 2013-03-22 22:13:43