Explain hashcode() and equals()
The hashCode() and equals() methods are fundamental in defining the behavior of objects in collections like HashMap, HashSet, and other data structures that rely on hashing.
Table of Contents
hashCode() Method
Purpose:
- The hashCode() method returns an integer representation of the memory address of the object.
- It is used to quickly narrow down the search to a smaller subset of possible matches when searching in collections.
Characteristics
- Should consistently return the same integer, provided no information used in equals() comparisons is modified.
- If two objects are equal according to the equals(Object) method, then calling hashCode on each of the two objects must produce the same integer result.
equals() Method
Purpose
- The equals() method checks if two objects are considered equal.
- It is used to compare the actual data of the objects to determine equality.
Characteristics
- Reflexive: For any non-null reference value x, x.equals(x) should return true.
- Symmetric: For any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- Transitive: For any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- Consistent: For any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false.
Importance in Java
Hash-based Collections
- Proper implementation of hashCode() and equals() is crucial for the correct functioning of hash-based collections like HashMap, HashSet, and Hashtable.
- They ensure that objects are stored and retrieved efficiently and correctly.
Performance
  A good hashCode() implementation improves the performance of hash-based collections by reducing the number of hash collisions.
Contract Adherence:
  Failure to adhere to the contract between equals() and hashCode() can result in incorrect behavior of collections, such as not being able to find objects that have been inserted.
Example
Example
Here’s an example demonstrating the implementation of hashCode() and equals():
java
public 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 && name.equals(person.name);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
public static void main(String[] args) {
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Alice", 30);
Person person3 = new Person("Bob", 25);
System.out.println("person1 equals person2: " + person1.equals(person2)); // true
System.out.println("person1 equals person3: " + person1.equals(person3)); // false
System.out.println("person1 hashCode: " + person1.hashCode());
System.out.println("person2 hashCode: " + person2.hashCode());
System.out.println("person3 hashCode: " + person3.hashCode());
}
}
Explanation
equals() Method
- Compares the name and age fields of the Person objects.
- Returns true if both fields are equal; otherwise, returns false.
- hashCode() Method:
- Computes the hash code using the name and age fields.
- The hash code is calculated using the formula: result = 31 * result + age, where 31 is a prime number chosen to reduce collisions.
- Main Method:
- Creates three Person objects.
- Compares the objects using equals() and prints the results.
- Prints the hash codes of the objects.