Equal() and hashcode() in Java

Serxan Hamzayev
Javarevisited
Published in
3 min readDec 20, 2022

--

In Java, the equals() the method is used to determine if two objects are equal. It is defined in the Object class, which is the root of the Java class hierarchy, and it is inherited by all Java classes. The equals() method takes an object as an argument and returns a boolean value indicating whether the object is equal to the invoking object.

The hashCode() the method is used to return a hash code value for an object. A hash code is a numerical value that is used to identify an object in a hash-based data structure, such as a hash table. The hashCode() method is also defined in the Object class and is inherited by all Java classes.

It’s important to override both equals() and hashCode() methods when you want to use your own objects as keys in a hash-based data structure, such as a HashMap. If you override the equals() method, you should also override the hashCode() method, because the hashCode() the method is used to determine the location of an object in a hash-based data structure, and if two objects are equal, they must have the same hash code.

Here’s an example of how to override equals() and hashCode() in a Java class:

public class Employee {
private String name;
private int age;

public Employee(String name, int age) {
this.name = name;
this.age = age;
}

@Override…

--

--