How to compare two java objects

Roy Hinkley picture Roy Hinkley · Apr 17, 2013 · Viewed 181.1k times · Source

I have two java objects that are instantiated from the same class.

MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();

If I set both of their properties to the exact same values and then verify that they are the same

if(myClass1 == myClass2){
   // objects match
   ...

}

if(myClass1.equals(myClass2)){
   // objects match
   ...

}

However, neither of these approaches return a true value. I have checked the properties of each and they match.

How do I compare these two objects to verify that they are identical?

Answer

John Kugelman picture John Kugelman · Apr 17, 2013

You need to provide your own implementation of equals() in MyClass.

@Override
public boolean equals(Object other) {
    if (!(other instanceof MyClass)) {
        return false;
    }

    MyClass that = (MyClass) other;

    // Custom equality check here.
    return this.field1.equals(that.field1)
        && this.field2.equals(that.field2);
}

You should also override hashCode() if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:

@Override
public int hashCode() {
    int hashCode = 1;

    hashCode = hashCode * 37 + this.field1.hashCode();
    hashCode = hashCode * 37 + this.field2.hashCode();

    return hashCode;
}

See this question for more details on implementing a hash function.