Reputation: 21
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, Square
, with the element of 0. 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.
Upvotes: 1
Views: 63
Reputation: 126
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(with GameBoard
renamed gameboard
, per java naming conventions):
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;
}
Upvotes: 1