Adding objects to array list end up with same values

Bit of an odd one. I am trying to create a board game (backgammon) and have created an object called piece. On my board I am trying to create an array list of pieces

ArrayList<piece> pieces = new ArrayList<piece>();

piece newPiece = new piece(1, 1, "red", "top");
piece newPiece2 = new piece(1, 2, "black", "top");

pieces.add(newPiece);
System.out.println(newPiece.getCol());
pieces.add(newPiece2);
System.out.println(newPiece2.getCol());

I was expecting the outputs to be 'red' then 'black', but I actually get 'black' then 'black'? Any suggestions why this might be happening?

Jon Skeet
people
quotationmark

The ArrayList is a red-herring here - you're never even fetching the pieces out again. You'll see exactly the same behaviour with just this code:

piece newPiece = new piece(1, 1, "red", "top");
piece newPiece2 = new piece(1, 2, "black", "top");
System.out.println(newPiece.getCol());
System.out.println(newPiece2.getCol());

I strongly suspect that the bug is in the piece class - whatever variable you're using to store the colour is probably a static variable instead of an instance variable. Static variables are related to the type rather than any specific instance of the type, so if you overwrite the value of a static variable in a constructor, you'll always see that value when you fetch it again. You want different state for each instance, so you should have instance variables.

(Additionally, you should improve your names, e.g. Piece instead of piece, and getColor instead of getCol.)

people

See more on this question at Stackoverflow