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.
Figure 1: Object references pointing to different objects with equal states.
In figure 2, two object references each point to the same object:
Figure 2: Object references pointing to the same object.
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
* 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
true if the other object has an identical state; otherwise
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
[This page last updated 2020-12-23 at 12h13 Toronto local time.]
© 2007–2021 Hersch, Bear & Company Limited. All rights reserved. “Grammar Authority,” “grammarauthority.com,” “touque.ca,” and “Canada’s Thinking Cap” are trademarks of Hersch, Bear & Company Limited. All other trademarks and copyrights are the property of their respective owners.