46. equals() and hashCode()

The equals() and hashCode() methods are defined in java.lang.Object. Since Object is the superclass of all Java objects, these two methods are available for all objects. Their main goal is to provide an easy, efficient, and robust solution for comparing objects, and to determine whether they are equal. Without these methods and their contracts, the solution relies on the big and cumbersome if statements meant to compare each field of an object.

When these methods are not overridden, Java will use their default implementations. Unfortunately, the default implementation is not really serving the goal of determining whether two objects have the same value. By default, equals() checks identity. In other words, it considers ...

Get Java Coding Problems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.