Thursday 4 April 2013

How to override equals and hashCode method in Java

How to override equals() and hashCode() method in Java


In Java, Object class has methods called hashCode () and equals(). They are the basic methods and part of core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object.

The Default implementation of equals() method is  provided by Object class compares memory location and only return true if two reference variable are pointing to same memory location it means essentially they are the same object. Stringoverrides equals,  whose implementation of equals() method return true if content of two String objects are exactly same. Similarly IntegerWhich is a wrapper class also overrides equals() method to perform numerical comparison and Other Wrapper classes(like Long, Boolean, Character, Double, Float, Byte, Short) also overrides equals() method according to return their business logic.

As HashTable and HashMap in Java depends on the principle of hashing where it is necessary to override equals() and hashCode() method for comparing keys and values, Java provides following rules to override equals() method. As per below rules which is mentioned in java api, equals() method in Java should be:


1) Reflexive: Object must be equal to itself.
2) Symmetric: if obj1.equals (obj2) is true then obj2.equals (obj1) must return true.
3) Transitive: if obj1.equals (obj2) is true and obj2.equals (obj3) is true then obj3.equals (obj1) must return true.
4) Consistent: multiple invocation of equals () method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of their property is modified.
5) Null comparison: comparing any object to null must return false and should not result in “NullPointerException”. For example obj1.equals (null) should return false,



The Contract between Equals()and hashCode() method in Java are:-

1) If two objects are equal by equals() method then their hashcode must be the same.
2) If two objects are having the same hashCode then it doesn’t mean that both objets are equal by equals() method, they might be unequal also. In other terms If two objects are not equal by equals() method then their hashcode might be the same or different.

Steps to override the equals() and  hashCode() method is as follows:-

I have created a class Animal where I have overrided the equals() and hashCode() method,

package com.gaurav.javaprograms;

public class Animal {
    private int age;

    public Animal(int ageVar) {
        this.age = ageVar;
    }

    public int hashCode() {
        return age;
    }

    public boolean equals(Object obj) {
        boolean flag = false;
        Animal animal = (Animal) obj;
        if (animal.age == age) {
            flag = true;
        }
        return flag;

    }
}

This is the Test Class for the above Animal class where I have created two instances of Animal objects and comparing the both instances using equals() method.

package com.gaurav.javaprograms;

public class TestEqualsAndHashCode {
    public static void main(String args[]) {

        Animal animal1 = new Animal(12);
        Animal animal2 = new Animal(12);

        System.out.println("Both Animal objects are equal-"
                + animal1.equals(animal2));
        System.out.println("Animal objects references are equal-" + (animal1 == animal2));

    }
}

No comments:

Post a Comment