Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

Java Hashmap if statement check doesnt work


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...