Java Record Custom equals and hashCode

1. Introduction

In this blog post, we will explore how to customize the equals and hashCode methods in Java Records. Introduced in Java 16, records provide an efficient way to create immutable data classes. While they automatically generate equals and hashCode methods, certain scenarios might require custom implementations.

Definition

The equals method in Java is used for logical equality comparison between objects, and hashCode provides an integer representation of the object's memory address. In Java Records, these methods are automatically generated based on the record's state, but they can be overridden for custom behavior.

2. Program Steps

1. Define a Java Record.

2. Override the equals and hashCode methods in the record.

3. Demonstrate the use of these methods with record instances.

3. Code Program

// Record with custom equals and hashCode methods
public record Employee(String name, int id) {

    // Overriding equals method
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id; // Comparing based on id only
    }

    // Overriding hashCode method
    @Override
    public int hashCode() {
        return Objects.hash(id); // HashCode based on id only
    }
}

public class Main {
    public static void main(String[] args) {
        Employee employee1 = new Employee("Alice", 1001);
        Employee employee2 = new Employee("Bob", 1001);

        // Using the overridden equals and hashCode methods
        System.out.println("Equal: " + employee1.equals(employee2));
        System.out.println("HashCode of Employee1: " + employee1.hashCode());
        System.out.println("HashCode of Employee2: " + employee2.hashCode());
    }
}

Output:

Equal: true
HashCode of Employee1: 1001
HashCode of Employee2: 1001

Explanation:

1. The Employee record is defined with fields name and id.

2. The equals method is overridden to compare Employee objects based on their id field only.

3. The hashCode method is also overridden to compute the hash code based on the id field.

4. In the main method, two Employee instances with different names but the same id are created.

5. The equals method correctly identifies these instances as equal due to their identical ids, and the hashCode method generates the same hash code for both, reflecting their equality.

6. This example demonstrates how equals and hashCode can be customized in Java Records for specific equality and hashing requirements.


Comments