I repeatedly heard about what is recommended when overriding equals override and hashCode . But so it is recommended that it seems that you will not refuse.

Is there any agreement that if I redefine equals , then hashCode must also be redefined, otherwise the code will not be considered correct? Or is it just a recommendation?

    2 answers 2

    If you reimplement equals(...) , but do not redefine hashCode() , then in some cases your program will behave incorrectly.

    In particular, this manifests itself for objects that are keys in a HashMap .

    If objects are equal, then their hash codes must be equal.

      To maintain a common contract - equal objects must have the same hash code.