contract between hascode and equal - amresh087/newronaRepos GitHub Wiki

If two objects are equal according to the equals(Object) method, then calling the hashcode() method on each of the two objects must produce the same integer result.

In order to achieve a fully working custom equality mechanism, it is mandatory to override hashcode() each time you override equals(). Follow the tips below and you'll never have leaks in your custom equality mechanism:

  • If two objects are equal, they MUST have the same hash code.

  • If two objects have the same hash code, it doesn't mean that they are equal.

  • Overriding equals() alone will make your business fail with hashing data structures like: HashSet, HashMap, HashTable ... etc.

  • Overriding hashcode() alone doesn't force Java to ignore memory addresses when comparing two objects.

Summary with Example