5.9 Comparing Objects

5.9.1 The equals Method

Often, we want to compare whether two objects are equal; typically, we will say that two objects are equal if they have the same data. If we use the equality operator (==) to compare object references, however, we are comparing the value of the object references. In other words, we are comparing whether the object references point to the same object, that is, the same memory location. To compare object data, we need to use the equals method, which all classes inherit from the Object class. Many classes provide a custom version of the equals method. The API of the equals method is the following:

public boolean equals( Object ob )

Typically, the equals method returns true if the data in the parameter ...

Get Java Illuminated, 5th 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.