touque.ca > Education Commons > Java > Resources > Equals

equals Method

The boolean equals method tests whether two objects have equal states. For example:

someObject.equals(someOtherObject) // see figure 1

Note that testing whether two objects have the same state (that is, are equal) is different than testing whether two object references point to the same object:

someObject == someOtherObject // see figure 2

Cay Horstmann, in his classic text book Big Java (2002: John Wiley & Sons, Inc. ISBN 0-471-40248-6), illustrates this difference with the example of a Coin class. In figure 1, two object references each point to a different object; each of the objects has an identical state.

two object references, each pointing to different objects with equal states
Figure 1: Object references pointing to different objects with equal states.

In figure 2, two object references each point to the same object:

two object references, each pointing to the same object
Figure 2: Object references pointing to the same object.

Implementation

Programmers are responsible for implementing the equals method whenever they create a class whose objects might be compared. To do so, they must override the equals method of the Object class. Since this method takes an Object as its parameter, it will be necessary to typecast the Object to the class under consideration. For example, if Coins are being compared for equality, the otherObject parameter must be typecast as a Coin:

/**
 * Indicates whether another object has a state identical to this object’s state.
 *
 * @param otherObject the object whose state is compared to this object’s
 * @return true if the other object has an identical state; otherwise false
 */
public boolean equals(Object otherObject)
{
   if (otherObject == null) return false;
   if (this.getClass() != otherObject.getClass()) return false;

   Coin other = (Coin)otherObject;

   // actual comparison goes here

touque.ca > Education Commons > Java > Resources > Equals

[This page last updated 2020-12-23 at 12h13 Toronto local time.]