Dung (Donny) Nguyen

Senior Software Engineer

Equals() and hashCode() methods

The equals() and hashCode() methods are used to compare objects and determine their equality and placement in hash-based collections like HashMap, HashSet, and Hashtable. Here’s how they work:

equals() Method

@Override
public boolean equals(Object obj) {
    if (this == obj) return true; // Same reference
    if (obj == null || getClass() != obj.getClass()) return false; // Different class or null
    MyClass other = (MyClass) obj;
    return this.field == other.field; // Compare meaningful fields
}

hashCode() Method

@Override
public int hashCode() {
    return Objects.hash(field1, field2); // Generate hash based on fields
}

Key Points

Example:

class Employee {
    private int id;
    private String name;

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Employee employee = (Employee) obj;
        return id == employee.id && Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

Here, equals() checks if two Employee objects have the same id and name, and hashCode() ensures that these objects return the same hash code if they are equal.

By properly overriding both methods, we ensure that the object behaves as expected in hash-based collections.

What happens if hashCode() method always returns the same value?