Use of hashcode() and equals()


Use of hashCode() and equals(). 

Object class provides two methods hashcode() and equals() to represent the identity of an object. It is a common convention that if one method is overridden then other should also be implemented.

Before explaining why, let see what the contract these two methods hold. As per the Java API documentation:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
  • It is NOT required that if two objects are unequal according to the equals(Java.lang.Object) method, then calling the hashCode() method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Now, consider an example where the key used to store the in Hashmap is an Integer. Consider that Integer class doesn’t implement hashcode() method. Just for this example The code would look like:

  map.put(new Integer(5),”Value1″);
String value = (String) map.get(new Integer(5));
System.out.println(value);
//Output : Value is null

Null value will be displayed since the hashcode() method returns a different hash value for the Integer object created at line 2and JVM tries to search for the object at different location.

Now if the integer class has hashcode() method like:

public int hashCode(){
return value;
}

Everytime the new Integer object is created with same integer value passed; the Integer object will return the same hash value. Once the same hash value is returned, JVM will go to the same memory address every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.

Another step of caution that needs to be taken is that while implementing the hashcode() method the fields that are present in the hashcode() should not be the one which could change the state of object.

Consider the example:

publicclass FourWheeler implements Vehicle {

 

      private String name;

      privateintpurchaseValue;

      privateintnoOfTyres;

      public FourWheeler(){}

 

public FourWheeler(String name, int purchaseValue) {

            this.name = name;

            this.purchaseValue = purchaseValue;

      }

      publicvoid setPurchaseValue(int purchaseValue) {

            this.purchaseValue = purchaseValue;

      }

 

      @Override

      publicint hashCode() {

            finalint prime = 31;

            int result = 1;

            result = prime * result + ((name == null) ? 0 : name.hashCode());

            result = prime * result + purchaseValue;

            return result;

      }

}

FourWheeler fourWObj = new FourWheeler(“Santro”,”333333);
map.put(fourWObj,”Hyundai);
fourWObj.setPurchaseValue(“555555)
System.out.println(map.get(fourWObj));
//Output: null

We can see that inspite of passing the same object the value returned is null. This is because the hashcode() returned on evaluation will be different since the purchaseValue is set to ‘555555’ from ‘333333’. Hence we can conclude that the hashcode() should contain fields that doesn’t change the state of object.

One compatible, but not all that useful, way to define hashCode() is like this:

public int hashcode(){
return 0;
}

This approach will yield bad performance for the HashMap. The conclusion which can be made is that the hashcode() should(not must) return the same value if the objects are equal. If the objects are not equal then it must return different value.

Overriding equals() method

Consider the example:

publicclass StringHelper {

 

      private String inputString;

     

      public StringHelper(String string) {

            inputString=string;

      }

 

      @Override

      publicint hashCode() {

            returninputString.length();

      }

   

 

      publicstaticvoid main(String[] args) {

           

            StringHelper helperObj = new StringHelper(“string”);

            StringHelper helperObj1 = new StringHelper(“string”);

            if(helperObj.hashCode() == helperObj1.hashCode()){

                  System.out.println(“HashCode are equal”);

            }

            if(helperObj.equals(helperObj1)){

                  System.out.println(“Objects are equal”);

            }else{

                  System.out.println(“Objects are not equal”);

            }

 

      }

 

      public String getInputString() {

            returninputString;

      }

 

// Output:
HashCode are equal
Objects are not equal

We can see that even though the StringHelper object contains the same value the equals method has returned false but the hashcode method has return true value.

To prevent this inconsistency, we should make sure that we override both methods such that the contract between both methods doesn’t fail.

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

1. 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.

2. 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.

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

4. 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

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

The correct implementation if equals method for the StringHelper class could be:

@Override

      publicboolean equals(Object obj) {

            if (this == obj)

                  returntrue;

            if (obj == null)

                  returnfalse;

            if (getClass() != obj.getClass())

                  returnfalse;

            final StringHelper other = (StringHelper) obj;

            if (inputString == null) {

                  if (other.inputString != null)

                        returnfalse;

            } elseif (!inputString.equals(other.inputString))

                  returnfalse;

            returntrue;

      }

 

Advertisements

24 thoughts on “Use of hashcode() and equals()

    1. May befor (var i = 0; i < this.length; i++) {notfor (i = 0; i < this.length; i++) {And I think if we cash this.length it was more faster, finllay:String.prototype.hashCode = function(){ var hash = 0, len = this.length; if ( len === 0 ) return hash; for( var i = 0; i < len; ++i ) { char = this.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash = hash & hash; // Convert to 32bit integer } return hash;}

  1. In the last equals method the first statement is “if (this == obj) return true;”. Hash code could be same for different object that are running in a application. In that case the equals method would fail. Isn’t it ?

  2. please test the code samples and the post it
    map.put(new Integer(5),”Value1″);
    String value = (String) map.get(new Integer(5));
    System.out.println(value);
    //Output : Value is null

    output is “Value1” instead of null as Integer class is immutable so it returns the same hash code every time…

    1. You are correct. I have said in a line above “consider if Integer class doesnt have a hashcode method”
      Probably i should change the example or make more obvious there .

  3. The JAVADOC mentions:

    – If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
    – It is NOT required that if two objects are unequal according to the equals(Java.lang.Object) method, then calling the hashCode() method on each of the two objects must produce distinct integer results.

    The article says:
    – The conclusion which can be made is that the hashcode() should(not must) return the same value if the objects are equal.
    – If the objects are not equal then it must return different value.

    I think the above statement should be inversed. The first one is a must while second is recommended for optimal performance.

  4. Example is ok. but take two attributes in StringHelper class then check equality, it does not work.. Can anyone please explain this …..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s