to start, I suggested you do the following test (does not solve the question, but eventually shows the real problem - not related to HashMap
):
System.out.println(new Square("black") != new Square("black"));
to compare objects (by content) you should use equals
, like is actually being done inside Square
. Reason: ==
and !=
, when applied to objects, do not compare the content, but only if it is the same instance (same memory) or not. new
will always, if not terminated abruptly, create a new instance. Same reason for new String("abc") != new String("abc")
Solution: add/implement/override the equals
method in Square
AND use it to compare them. This method would compare the value stored in status
.
Note: when overriding the equals
method it is also recommended to override the hashCode
method.
Workaround: declare constants - only once, globally available, used everywhere:
public final Square BLACK = new Square("black");
...
if used consistently, these can be compared with ==
and !=
- implementing equals
is still recommended.
Since this is a dangerous solution, some developer may create a new instance and it will fail again... see next solution.
Better solution: create an enum
for this 3 values:
public enum Square {
EMPTY, BLACK, WHITE;
}
no need for equals
and can be compared directly with ==
and !=
(or equals
) (but will need to override toString
or implement some method for correct output)
assuming code has different instances of white
, black
and empty
, based on board.board.get(move) == empty
always returning false
Note: also check Joop's answer!!