The Object’s equals Method

Paul Ngugi - Jun 10 - - Dev Community

Like the toString() method, the equals(Object) method is another useful method defined in the Object class. Another method defined in the Object class that is often used is the equals method. Its signature is

public boolean equals(Object o)

This method tests whether two objects are equal. The syntax for invoking it is:

object1.equals(object2);

The default implementation of the equals method in the Object class is:

public boolean equals(Object obj) {
return (this == obj);
}

This implementation checks whether two reference variables point to the same object using the == operator. You should override this method in your custom class to test whether two distinct objects have the same content.

The equals method is overridden in many classes in the Java API, such as java.lang.String and java.util.Date, to compare whether the contents of two objects are equal. The equals method in the String class is inherited from the Object class and is overridden in the String class to test whether two strings are identical in content.

You can override the equals method in the Circle class to compare whether two circles are equal based on their radius as follows:

public boolean equals(Object o) {
if (o instanceof Circle)
return radius == ((Circle)o).radius;
else
return this == o;
}

The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The equals method is intended to test whether two objects have the same contents, provided that the method is overridden in the defining class of the objects. The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object. Using the signature equals(SomeClassName obj) (e.g., equals(Circle c)) to override the equals method in a subclass is a common mistake. You should use equals(Object obj).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .