The answer: Thanks for all the help! Like most of you said the solution was to make a new 2d int array, and copy the values from the old one. This was the function i made, and i can then add the new board into the hashmap, as a new key.
void newboard(){
NewBoard = new int[N][N];
for(int n = 0; n < N; n++){
for(int i = 0; i < N; i++){
NewBoard[n][i] = CurrentBoard[n][i];
}
}
}
The Question:
I have the following code, that puts an 3x3 board along with a list of integers, specifically (f, g, h) into a hashmap. The Board CurrentBoard is an unsolved 8-puzzle.
public static HashMap<int[][], List<Integer>> map = new HashMap<>();
map.put(CurrentBoard, fgh);
I initialise the hashmap, and for the rest of the program I want to iterate through the map, to get the board I need. Every entry of the map will be a specific state of the 8-puzzle board after the '0' position has been moved.
This is my way of doing that. The 'cv' variable is just to choose the board (key) with the lowest "f" value.
for(Map.Entry<int[][], List<Integer>> mapentry : map.entrySet()) {
if (cv > mapentry.getValue().get(0)) {
cv = mapentry.getValue().get(0);
CurrentBoard = mapentry.getKey();
fgh = mapentry.getValue();
}
}
Now that I've got a Board in the "CurrentBoard" variable, I want to move the '0' up one row. So I've called this function:
void moveUp(){
NewBoard = CurrentBoard;
memory = NewBoard[ZeroPositionX][ZeroPositionY - 1];
NewBoard[ZeroPositionY- 1][ZeroPositionX] = 0;
NewBoard[ZeroPositionY][ZeroPositionX] = memory;
}
Then I do a couple of (for this question) unimportant checks, and recalculate the fgh values for this NewBoard.
I then proceed to put the NewBoard along with the fgh values into the hashmap by using
map.put(NewBoard, fgh);
My problem is that this replaces the current key in the hashmap. In other words, instead of adding a key and a value to the hashmap, it replaces the already existing key and value. I have tried printing both the New and current boards to ensure they are different.
When I print the entrySet() of the hashmap it only gives me the latest entry. In other words the board, and the values after having moved the '0'.
for(Map.Entry mapentry : map.entrySet()){
System.out.println(mapentry);
}
Why does adding the new key and value to the hashmap not work?
Endnote: I am new to Java, so some of this is probably sub-optimal. I will do my best to explain more in detail if necessary.