4

What problems can arise if the result of the equals() and hashCode() methods changes across the lifetime of an object?

Thank you!

Minar Mahmud
  • 2,577
  • 6
  • 20
  • 32
yoX64
  • 43
  • 3
  • possible duplicate of [What issues should be considered when overriding equals and hashCode in Java?](http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java) – Dave Jan 31 '15 at 19:30
  • you will probably end up with some memory leak – rodrigoalvesvieira Jan 31 '15 at 19:32
  • As long as the contract between those two methods is not broken, it should be fine. It is expected to change the result when you modify the state of the object. – RP- Jan 31 '15 at 19:32
  • I disagree that this is a duplicate of the linked question. This refers to changing the implementation of an existing `equals` or `hashCode` method, not to overriding the superclass methods when creating a new type. – Bobulous Jan 31 '15 at 19:52

1 Answers1

7

One problem is that you won't be able to find that object in a HashSet or a HashMap (when that object is a key in the Map) if its hashCode changes after to add it to the Collection.

Changing the result of equals during the lifetime of an object may result in breaking some Collections. For example, you may find you have duplicate objects in your Set, because at the time the second object was added to the Set, they weren't equal.

Eran
  • 387,369
  • 54
  • 702
  • 768