Using equals and hashCode methods in Java


In Java, comparing two primitive data types can be achieved by using == operator, but to compare reference data type we need to provide the equals method.

By default every class in Java inherits from Object class which provides default implementation of equals method. It simply compares reference and return true and false accordingly. Lets see it through example.

class Student
{

private int rollno;
private String name;
private double marks;
public Student(int rollno, String name, double marks)
{
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
}

public class Test
{
public static void main(String args[])
{
Student s1 = new Student(10, “Test”, 20.00);
Student s2 = new Student(10, “Test”, 20.00);
Student s3 = s1;

System.out.println(s1==s2); //false
System.out.println(s1==s3); //true
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equals(s3)); //true
}
}

We can see clearly from first three line in main that s1 and s2 holds the same data for student, where as s1 and s3 points to same instance or stores the same reference.
In print statements, we can see == and equals both gives the same output, on the basis of reference or on basis of what they are pointing to.

This is the case where we need to provide custom way for comparing the object. For example if two rollno is same than the students are same. Lets add the equals method [ overriding the default behavior ]public boolean equals(Object o)
{
if(o==null)
return false;
if(o.getClass()!=this.getClass())
return false;
if(this==o)
return true;
Student temp = (Student)o;
if(rollno==temp.rollno)
return true;
else
return false;}The equals method now looks for equality on roll no. Hence the output will be

System.out.println(s1==s2); //false
System.out.println(s1==s3); //true
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //true

When adding equals method one should ensure that equals method is

  • Reflexive       o.equals(o) should return true
  • Symmetric    o.equals(o1) should be same as o1.equals(o)
  • Transitive      for a,b,c a.equals(b) true means b.equals(c), and a.equals(c)  should be true.
  • Consistent    for o and o1 o.equal(o1) if returns true, throughout program it should be true.
  • Any null value reference should return false.

Understanding hashcode:

It is an integer value for the object, which is nothing but converting the internal address in to the an integer. It is widely used by the data structures like hash map, hash table etc.. which is part of Java Collection.

Hash code of an objects allows the data structures algorithm to create and put object in compartment, for  better retrieval. Normally algorithms puts objects with same hash code in same compartment.

As per Java Docs, the general contract for hash code is :

  • 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 hash tables.

If we do not override the hashcode method, in that case two equal objects will be equal but still they will be not equal when stored in hash based data structures.

While creating the hashcode ensure that it creates hash code logic base on the equals method. In our case, we are using roll no for deciding the equality so our hashcode method will also use roll no. In simplest form it will be

public int hashCode()
{
return rollno;
}

In simple words, if we are overriding the equals method we should override the hashCode method also.

Leave a comment

Your email address will not be published. Required fields are marked *