Good day.

Faced the following problem. I have a class all fields which changeable from outside. It was necessary to override the equals() method for this class. According to the rule, the hashCode() method must also be changed. But here's the problem: all the fields of an object used in the equals() method for comparison often change their values, and if I use them to calculate hashCode , then for the same object its hashcode will change with time.

The first question is: how should you override hashCode() in this case?

And the second: to comply with the rule: "for the same object, the hashCode() method should return the same value" only if we are going to use class objects as keys with hash-based collections? Otherwise it is not necessary?

    1 answer 1

    In the situation described by you I do not see any problem. Changing the state of an object entails a change in the hashcode value, and this is normal, it should be.

    Regarding the second question: when redefining equals() always override hashCode() , it may not always be necessary, but if you suddenly need it, you will search for the cause of the problem for a long time, if you do not override hashCode() .