java

How to override the equals() and hashCode() methods in Java

The equals() and hashCode() methods. These two methods are defined in the java.lang.Object class. We use the equals() method to compare whether two objects are equivalent, which means that the two objects themselves (not the references) are equal. To check whether the object references are equal or not, we use the == operator which uses the hash code value of the object to evaluate it.

The hashCode() method is used to generate a hash code value for an object and this hash code value is used by some collection classes to compare objects, which increases the performance of large collections of objects.

Let’s define our Student class for which we’ll redefine the hashCode() and equals() methods.
 

 

public class Student {
	
	private String name;
	private int age;
	
	public Student(){}
	
	public Student(String name, int age) {
		 this.age = age;
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
}

 

Redefine the HashCode method

Here is the example code we added to the Student class to override the hashCode() method.

@Override
public int hashCode() {
	int result = 17;
	result = 31 * result + (name == null ? 0 :name.hashCode());
	result = 31 * result + age;
	return result;
}

Using 31 as a hash is just to ensure that the value of the hashcode will be different for each object. You need to calculate the hash for different members and return the total as a unique hash code.
 

 

Redefine the equals method

Here is the example code that we added to the Student class to override the equals() method.

@Override
public boolean equals(Object obj){
	
	if(obj == null) return false;
	
	if(obj instanceof Student && this == obj) return true;
	
	Student student = (Student)obj;
	
	if(age != student.age) return false;

	if(name != null && !name.equalsIgnoreCase(student.name)) return false;

	return true;
}

Run the code below, to verify the override of the equals() and hashCode() methods.

public class Test {
	public static void main(String [] args){
		
		Student student1 = new Student("Alex", 22);
		Student student2 = new Student("Alex", 23);
		
		System.out.println(student1.equals(student2)); // false
		
	}
}

 

The contract between Hashcode and Equals:
  • If two objects are equal according to the equals() method, their hash codes must be the same.
  • If two objects are not equal according to the equals() method, their hash code may be the same or different.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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