11.7. Implementing the equals(), hashCode(), and compareTo() Methods

The majority of the non-final methods of the Object class are meant to be overridden. They provide general contracts for objects, which the classes overriding the methods should honor.

It is important to understand how and why a class should override the equals() and hashCode() methods. Implementation of the compareTo() method of the Comparable interface is closely related to the other two methods.

Objects of a class that override the equals() method can be used as elements in a collection. If they override the hashCode() method, they can also be used as elements in a HashSet and as keys in a HashMap. Implementing the Comparable interface allows them to be used as elements in ...

Get Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second Edition 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.