What is Java object equals contract?

The object equals contract indicates that when two objects are equal, their hash codes must also be the same. It’s a general agreement for all Java objects used in hash-based collections. Its main purpose is to optimize performance when working e.g. with HashMap or HashSet.

You may hear that when you implement the equals() method for your class, you should also implement the hashCode() method. That’s the practical approach for fulfilling the equals contract.

If you want to know more details why the contract is so important, keep on reading.
Continue reading “What is Java object equals contract?”