Copying an array from an ArrayList element
I am building a Java based game in Swing which is essentially a Jbuttons grid
I have an object called Cell, which is a custom JButton with additional parameters for storing objects. Game grid is presentedCell[][]
I have an arraylist of type Cell[][]
so that I can save the state of the gamegrid after every move. If I want to undo a move, I need to copy the last item of the ArrayList to the games grid so that it appears in the UI.
My gamegrid panelHolder
and my arraylist moveHolder
.
So far I have tried Collections.copy(panelHolder, moveHolder.get(moveHolder.size()));
, which will not compile due to the fact that "arguments are not valid for type Cell[][]
"
I have also tried System.arraycopy(moveHolder.get(moveHolder.size()-1), 0, panelHolder, 0, panelHolder.length);
which throws and throws the exception. I originally thought it was related to moveHolder.size()-1
, but even how moveHolder.size()
it has the same problem.
I've found tons of questions on StackOverflow and others that both show these two ways to do it, but I can't seem to get it to work. Is there something more obvious I'm missing? Full class method:
public class UndoClass implements MoveCommand{
public ArrayList<Cell[][]> moveHolder = new ArrayList<Cell[][]>();
public Cell[][] execute(Cell[][] panelHolder) {
if (moveHolder.size() > 0){
Collections.copy(panelHolder, moveHolder.get(moveHolder.size()));
if (moveHolder.size() > 0){
moveHolder.remove(moveHolder.size());
}
}
System.out.println("Move Undone. Undos available:" + moveHolder.size());
return panelHolder;
}
public void addMove(Cell[][] panelHolder){
moveHolder.add(panelHolder);
}
public ArrayList<Cell[][]> getMoves(){
return moveHolder;
}
}
Cell class
public class Cell extends JButton {
int co_x = 0;
int co_y = 0;
ArrayList<Players> current = new ArrayList <Players>();
}
source to share
Just wanted to point out that our execute (...) method takes Cell [] [] as both a parameter and a return argument. This approach will force all your commands to keep copying your original parameter arrays into the return array. Note, if you don't need to sync the two, and you just use return arg, you don't need to worry about copying at all:
Cell[][] lastState = moveHolder.get(moveHolder.size()-1);
moveHolder.remove(moveHolder.size()-1);
return lastState; // Not updating the panelHolder array, just returning
But of course now the input parm and return are not synchronized. Instead, you can encapsulate this state into a single object to make your life easier. Something like this (note that execution now returns empty):
public ArrayList<GameState> previousStates = new ArrayList<GameState>();
public void execute(GameState currentState) {
if (previousStates .size() > 0) {
GameState lastState = previousStates.get(previousStates.size()-1);
currentState.restoreFrom(lastState);
previousStates .remove(moveHolder.size()-1);
}
}
Good luck with the game!
source to share