ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

Override equals and hashCode in Java

Equals and hashCode in Java are two fundamental method which is declared in Object class and part or 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.

 

equals method is also used to avoid duplicates on HashSet and other Set implementation and every other place where you need to compare Objects. Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object. Java recommends to override equals and hashCode method if equality is going to be define by logical way or via some business logic and many classes in Java standard library does override it e.g. String overrides equals,  whose implementation of equals() method return true if content of two String objects are exactly same. Integer wrapper class overrides equals to perform numerical comparison etc.

Since HashMap and Hashtable in Java relies on equals() and hashCode() method for comparing keys and values, Java provides following rules to override equals method Java. As per following rule equals method in Java should be:

 

1) Reflexive : Object must be equal to itself.

2) Symmetric : if a.equals(b) is true then b.equals(a) must be true.

3) Transitive : if a.equals(b) is true and b.equals(c) is true then c.equals(a) must be 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 there property is modified.

5) Null comparison : comparing any object to null must be false and should not result in NullPointerException. For example a.equals(null) must be false, passing unknown object, which could be null,  to equals in Java is is actually a Java coding best practice to avoid NullPointerException in Java.

 

Steps to Override equals method in Java

Here is my approach for overriding equals method in Java. This is based on standard approach most of Java programmer follows while writing equals method in Java.

 

1) Do this check -- if yes then return true.

2) Do null check -- if yes then return false.

3) Do the instanceof check,  if instanceof return false than return false from equals in Java , after some research I found that instead of instanceof we can use getClass() method for type identification because instanceof check returns true for subclass also, so its not strictly equals comparison until required by business logic. But instanceof check is fine if your class is immutable and no one is going to sub class it. For example we can replace instanceof check by below code

 

if((obj == null) || (obj.getClass() != this.getClass()))

        return false;

 

4) Type cast the object; note the sequence instanceof check must be prior to casting object.

 

5) Compare individual attribute starting with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks.  If first field does not match, don't try to match rest of attribute and return false. It’s also worth to remember doing null check on individual attribute before calling equals() method on them recursively to avoid NullPointerException during equals check in Java.

/**

 * Person class with equals and hashcode implementation in Java

 * @author Javin Paul

 */

public class Person {

    private int id;

    private String firstName;

    private String lastName;

 

    public int getId() { return id; }

    public void setId(int id) { this.id = id;}

 

    public String getFirstName() { return firstName; }

    public void setFirstName(String firstName) { this.firstName = firstName; }

 

    public String getLastName() { return lastName; }

    public void setLastName(String lastName) { this.lastName = lastName; }

 

    @Override

    public boolean equals(Object obj) {

        if (obj == this) {

            return true;

        }

        if (obj == null || obj.getClass() != this.getClass()) {

            return false;

        }

 

        Person guest = (Person) obj;

        return id == guest.id

                && (firstName == guest.firstName

                     || (firstName != null && firstName.equals(guest.getFirstName())))

                && (lastName == guest.lastName

                     || (lastName != null && lastName .equals(guest.getLastName())));

    }

   

    @Override

    public int hashCode() {

        final int prime = 31;

        int result = 1;

        result = prime * result

                + ((firstName == null) ? 0 : firstName.hashCode());

        result = prime * result + id;

        result = prime * result

                + ((lastName == null) ? 0 : lastName.hashCode());

        return result;

    }

   

}

Related Posts Plugin for WordPress, Blogger...
Flag Counter