Java Pushing an element into a single stack of a 2d array of stacks

I have a 2d array of stacks.

public Stack<Integer>[][] GameBoard = new Stack[3][3];

    //make square
    public Stack<Integer> Square = new Stack<>();

    public Stack<Integer>[][] FillBoard() {
        //initialize each square to have 0
        Square.push(0);
        //fill board with squares
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                GameBoard[i][j] = Square;
            }
        }
        GameBoard[1][1].push(1);
        return GameBoard;
    }

In this code, I give every stack in the 2d array a stack with the element of 0 (Square). When I then attempted to add an element to a certain stack (GameBoard[1][2].push(1)) it adds it to every stack in the array. so instead of {{0,0,0},{0,1,0},(0,0,0}} it returns {{1,1,1},{1,1,1},{1,1,1}}.
My only guess is that in the stack class, the list that stack uses is static?
Thank you in advance.

>Solution :

This is because you are setting every stack in Gameboard to the same stack , Square. So every time you push an element into any of the stacks in Gameboard, you will also be pushing that same element into every other stack in Gameboard. In other words, because you set every element in Gameboard to the same stack in your Fillboard() function, every element in Gameboard will always be identical. Instead, use a new stack for every element, like so:

public Stack<Integer>[][] GameBoard = new Stack[3][3];
    public Stack<Integer>[][] FillBoard() {
        //fill board with squares
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                Stack<Integer> Square = new Stack<>();
                Square.push(0);
                GameBoard[i][j] = Square;
            }
        }
        GameBoard[1][1].push(1);
        return GameBoard;
    }

Leave a Reply