Reputation: 15
I want to implement operation undo in game solitaire. I have I create function save which will copy actual state of elements and function load which will overrides actual elements with these copies. But when I call function save before some operation with card the function save values but when source of these values change these variables change too.
These variables are set in this class before constructor:
public class Game extends javax.swing.JPanel
like this
ArrayList<CardStack> undo_card_stack1 = new ArrayList<>();
Function save_undo simply copy actual state of values to these undo values like this:
private void save_undo()
{
undo_card_stack1.add(working_pack1_stack);
undo_card_stack2.add(working_pack2_stack);
....
Function is calls before every action with card - card is JLabel. What is not clear to me is why when debugging this part of code are values correctly set after save_undo() calls, but after operation with pop and push few lines after are values rewrites.
private void start_deckMouseClicked(java.awt.event.MouseEvent evt) {
save_undo();
discardPile_card = null;
if (!deck.isEmpty())
{
discardPile.deck.push(deck.pop());
...
Function load do exactly opposite of save and is calls when button clicked:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
load_undo();
}
Upvotes: 0
Views: 41
Reputation: 45806
If working_pack1_stack
is mutable (can be altered), it is possible for it to be changed even after it's been added to the ArrayList. All you're doing is adding a reference to the stack to the ArrayList. If you modify the stack, anywhere with a reference to it, including the list, will be altered as well.
Make a copy of your stack object and add that to the list to prevent it from being changed by outside code.
Upvotes: 1