Sunday, May 15, 2011

Steps that need to be taken into consideration while implementing equals method

  1. Use the == operator to check whether the incoming object is null. Its kind of performance optimization.
    public boolean equals(Object incomingObject) {
    if (incomingObject == null) return false;

  2. Use the == operator to check if the argument is a reference to this object. If so, return true. This is just a performance optimization, but one that is worth doing if the comparison is potentially expensive.

    public boolean equals(Object incomingObject){
    return true;

  3. Use the instanceof operator to check if the argument has the correct type.
    If not, return false. Typically, the correct type is the class in which the method occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equals contract to permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entry have this property.

    public boolean equals(){
    if (!(incomingObject instanceof MyClass)) return false;

    Note  : I have not checked like this:

    if(incomingObject instanceof MyClass)
    do something;

    The reason being instanceof returns true even when incomingObject is subclass object. So its important to check whether the object is type of class we are writing equals or not. If not, what is the point of writing further logic. Just return false, and leave.

  4. Cast the argument to the correct type. Because this cast was preceded by an instanceof test, it is guaranteed to succeed.

    public boolean equals(Object incomingObject){
    MyClass mc = (MyClass) incomingObject;

  5. For each “significant” field in the class, checks if that field of the argument matches the corresponding field of this object. If all these tests succeed, return true; otherwise, return false

  6. When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?

Writing the complete equals function

Finishing whole steps:

public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof MyClass)) return false;
MyClass mc = (MyClass) o;
return ... // compare members of mc

No comments:

Post a Comment