1

When overriding the equals operator for objects to compare fields, it is also said that you should override hashCode().

Is it ever the case that two objects would have all the same fields, but different hashCodes()? Why is it necessary to update both?

AJJ
  • 2,004
  • 4
  • 28
  • 42

2 Answers2

2

The main problem with not overriding both is that a lot of containers assume that both methods use the same strategy.

The typical cases are HashMaps, if you override one of equals()/hashCode() but not both (or override them inconsistently) , they will probably not work, because they use hashCode() to find the bucket your key should be, bu then use equals() to search inside that bucket. So it may end up searching for the given key in the wrong bucket!. Incidentally, this is why sometimes you don't find a key when get()ting it, but can find it by iterating over each element: iterating does not use hadhCode().

It is a similar reasoning as why you should never have a hashCode() that changes its value while the object is inside a HashSet/HashMap: by the time you search for your object, hashCode() might have changed and send you to an incorrect bucket.

gpeche
  • 21,974
  • 5
  • 38
  • 51
1

a.equals(b) implies that map.put(a, c); map.get(b) should yield c, where map is a Map, a and b are keys, and c is some value. In particular, a HashMap can do these operations very quickly, but relies on a.hashCode() and b.hashCode() to do so correctly. If a.hashCode() != b.hashCode() then they will not be recognised as equal keys and programs using HashMap will misbehave in a very frustrating and confusing manner. You should always assume that this is a possibility, even if you do not intend on doing this at the moment. Do not implement one without the other. It's also not that hard to do: your IDE can probably generate it (and equals) for you. Other data structures such as HashSet also use it.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89