Java Program To Implement A Custom equals() and hashcode() In Java
Chapter:
Miscellaneous
Last Updated:
07-10-2023 07:09:00 UTC
Program:
/* ............... START ............... */
import java.util.Objects;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
Person person3 = new Person("Alice", 25);
// Testing equals()
System.out.println("person1.equals(person2): " + person1.equals(person2)); // false
System.out.println("person1.equals(person3): " + person1.equals(person3)); // true
// Testing hashCode()
System.out.println("person1.hashCode(): " + person1.hashCode());
System.out.println("person3.hashCode(): " + person3.hashCode());
}
}
/* ............... END ............... */
Output
person1.equals(person2): false
person1.equals(person3): true
person1.hashCode(): 83109938
person3.hashCode(): 83109938
In this output:
person1.equals(person2) returns false because the name and age of person1 and person2 are different.
person1.equals(person3) returns true because the name and age of person1 and person3 are the same.
person1.hashCode() and person3.hashCode() return the same hash code value, which is 83109938, because
they have the same name and age values, and the hashCode() method generates a consistent hash code for
objects with the same attributes.
Notes:
-
In Java, the equals() and hashCode() methods are used to compare and hash objects, respectively. When you override these methods, you can define custom behavior for object comparison and hashing.
- In this example, we have a Person class with two fields: name and age. We override the equals() method to compare two Person objects based on their name and age fields. We also override the hashCode() method to generate a hash code based on these fields.
- When you create instances of the Person class and compare them using equals(), it will compare the name and age fields. If both fields are the same, the objects are considered equal. Additionally, calling hashCode() on these objects will generate a hash code based on the name and age fields, which is used in data structures like HashMap and HashSet for efficient storage and retrieval.