Push an element into a stack in an array with multiple stack pushes the element in all the stacks

StackOverflow https://stackoverflow.com/questions/23589938

  •  19-07-2023
  •  | 
  •  

سؤال

got a small problem when i am trying to push an element(Card) into a stack. I got an array containing 4 stacks, representing 4 piles of cards. But when i try to push the card into one of the stacks, it pushes in all of them instead. I bet there is just some stupid mistake in there, but my brain is not very alive atm..

Anyway the code:

stacks = new CardStack[4];   //array with 4 slots


   // Creating 4 stacks and placing each in one slot in the array
for (int i =0; i<4; i++){    
        CardStack<Card> stack = new CardStack<Card>(i+1);
        stacks[i] = stack;
    }

if i try to

stacks[0].push(currentCard);

it seems to be pushing the card into all of the stacks, and not just the stack at index 0 in the stacks array.

هل كانت مفيدة؟

المحلول

Looks like you have an array or List field inside CardStack to store the elements that will behave as a stack structure. Make sure this field is not static, otherwise it will be bound to the class, and all instances of the class will share the same array, List or whatever object it is.

More info:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top