In this article we will see "hashCode()" and "equals()" methods from java.lang.Object class in details. We will see different implementations and how to override them in efficient manner. "hashCode()" and "equals()" are from java.lang.Object class that is being inherited by every class in Java and hence all the classes in Java inherits the default implementation of these methods.


Usage of hashCode() and equals()

hashCode() method is used to get a identification integer number of object, the method is called upon. In default implementation from java.lang.Object class the declaration of hashCode() method is as follows.
public native int hashCode();
Here native indicated that the implementation of the method is done in JVM internally, in most JVM's this method returns the memory location of the object. In certain scenarios this is not enough and we need to implement some other algorithms inside hashCode() to get object's identification number, this we will see in rest part of the article.

equals() method on the other hand, as the name suggest is used to verify equality of two objects, the default implementation of equals() in java.lang.Object class is as follows:
public boolean equals(Object obj) { 
       return (this == obj); 
}
As the code implies, the method compares object's references to verify their equality, and return a boolean value accordingly. In certain cases we need to compare two objects on the basis of some properties or other aspects and not on their references and hence we overrides equals() default implementation, we will see this in next section.

Overriding equals() and hashCode() in Java

As we have seen hashCode() is used to get a identification Integer value, and by default the memory address of the object is returned. But we can override hashCode() in our own class to define user defined algo on calculating hashCode() of instances of the class. Before going forward and writing some code lets see the general contracts suggested by Java docs to override hashCode().

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

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

3) 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.


That means, two or more different objects may return same hashCode even if they are not equal; hashCode() is a identification number based on its consistency but not a unique identifier.

Lets assume we have a Employee class like this:

public class Employee {
	private Integer id;
	private String firstname;
	private String lastName;
	private int phone;

	public Integer getId() {
		return id;
	}

	public void setId(Integer 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;
	}

	public int getPhone() {
		return phone;
	}

	public void setPhone(int phone) {
		this.phone = phone;
	}
}

Now if we create two instances of the class with same id, and compare them for equality we will come up with a false value, because their references are different and default equals() checks for same references for equality.

		Employee e1 = new Employee();
		e1.setId(10);

		Employee e2 = new Employee();
		e2.setId(10);

		System.out.println("Are e1 and e2 equal: " + e1.equals(e2));

Now what if, we want to make a implementation like: if the id's of the two object is same the object's should be considered equal and equals() function should return a true.

That's where we need to override equals() in own class to have own implementation of equality of two objects. This will go like:

	@Override
	public boolean equals(Object o) {
		if (o == null) {
			return false;
		}
		if (o == this) {
			return true;
		}
		if (getClass() != o.getClass()) {
			return false;
		}

		Employee e = (Employee) o;
		return (this.getId() == e.getId());

	}

Now adding this overridden equals() in employee class and comparing e1 and e2 we will get a true. This will keep returning true until, two instances are of same class, none of them is a null and either their reference is same means they are same instance or their id is same.

But, we are not done yet, lets try to get hashCode() of two objects:

Employee e1 = new Employee();
		e1.setId(10);

		Employee e2 = new Employee();
		e2.setId(10);

		System.out.println("Are e1 and e2 equal: " + e1.equals(e2));
		System.out.println("e1 hashCode: "+e1.hashCode()+" e2 hashCode()"+e2.hashCode());
Output: Now the output would be like:

Are e1 and e2 equal: true
e1 hashCode: 289975132 e2 hashCode: 971648481


Here we can see even if two objects are equal, but their hashCode is not same, and this violets second point from hashCode() contract.

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

That means as per Java docs, if we override equals we must override hashCode() not to break the hashCode() contract.

Lets correct our Employee class by overriding hashCode() as well:


@Override 
public int hashCode() 
{ 
    final int PRIME = 31; 
    int result = 1; 
    result = PRIME * result + getId(); 
    return result; 
}

We are free to put any algo inside the body of hashCode() to calculate integer value, but be sure not to break all three contracts of hashCode() at any cost.

Here we are done with implementing, hashCode() and equals() for our Employee class, and this is not violating any contract. This will consider two employees equal if their id is same.


In this article we have seen, what are hashCode() and equals() methods and their default implementation in Object class, we have also seen how to override them in our own class. In upcoming articles we will see more about Java and other open source technologies.
  • By Techburps.com
  • Aug 25, 2015
  • Core Java