Partner – Microsoft – NPI (cat=Java)
announcement - icon

Microsoft JDConf 2024 conference is getting closer, on March 27th and 28th. Simply put, it's a free virtual event to learn about the newest developments in Java, Cloud, and AI.

Josh Long and Mark Heckler are kicking things off in the keynote, so it's definitely going to be both highly useful and quite practical.

This year’s theme is focused on developer productivity and how these technologies transform how we work, build, integrate, and modernize applications.

For the full conference agenda and speaker lineup, you can explore JDConf.com:

>> RSVP Now

1. Overview

In this tutorial, we’ll discuss Lombok’s @EqualsAndHashCode annotation, which generates the equals() and hashCode() methods for a class based on its fields.

2. Usage of @EqualsAndHashcode

The @EqualsAndHashCode annotation in Lombok generates the equals() and hashCode() methods for a given class, using all non-static and non-transient fields by default.

To customize the fields used, we can mark them with @EqualsAndHashCode.Include or exclude them with @EqualsAndHashCode.Exclude.

Let’s see an example to understand how it works:

@EqualsAndHashCode
public class Employee {
    private String name;
    private int id;
    private int age;
}

In this example, we’ve defined an Employee class with fields, name, id, and age, and annotated it with @EqualsAndHashCode.

Let’s take a look at the compiled class that includes the equals(), hashCode(), and canEqual() methods generated by Lombok:

public class EmployeeDelomboked {
    private String name;
    private int id;
    private int age;

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Employee)) {
            return false;
        } else {
            Employee other = (Employee) o;
            if (!other.canEqual(this)) {
                return false;
            } else if (this.getId() != other.getId()) {
                return false;
            } else if (this.getAge() != other.getAge()) {
                return false;
            } else {
                Object this$name = this.getName();
                Object other$name = other.getName();
                if (this$name == null) {
                    if (other$name == null) {
                        return true;
                    }
                } else if (this$name.equals(other$name)) {
                    return true;
                }

                return false;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof Employee;
    }

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        result = result * PRIME + this.getId();
        result = result * PRIME + this.getAge();
        Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        return result;
    }
}

When generating the equals() and hashCode() methods, Lombok also generates a canEqual() method that checks whether the compared object is an instance of the same class as the current object. It ensures that the equals() method proceeds with the comparison only when the objects are of the same class.

3. Excluding Fields From EqualsAndHashCode

Lombok offers several options to exclude specific fields from the method generation process. Let’s take a look at these options.

3.1. Exclude at Field Level With @EqualsAndHashcode.Exclude

We can use the @EqualsAndHashCode.Exclude annotation to instruct Lombok to exclude a field from the generation of equals() and hashCode() methods:

@EqualsAndHashCode
public class Employee {
    private String name;

    @EqualsAndHashCode.Exclude
    private int id;

    @EqualsAndHashCode.Exclude
    private int age;
}

In this example, we used the @EqualsAndHashCode.Exclude annotation to exclude the id and age fields from the equals() and hashCode() method generation. As a result, Lombok won’t use these fields to generate the methods:

public class EmployeeDelomboked {
    //fields names
    //standard getters and setters
    //equals() implementation
    @Override
    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        return result;
    }
}

We can see that the generated hashCode() method just uses the name field.

3.2. Exclude at Class Level

We can also use @EqualsAndHashCode.Exclude annotation at the class level to exclude the fields:

@EqualsAndHashCode(exclude = {"id", "age"})
public class Employee {
    private String name;
    private int id;
    private int age;
}

In this example, we didn’t annotate the fields directly with @EqualsAndHashCode.Exclude. Instead, we applied the annotation at the class level and specified the field names to exclude. Regardless, the resulting equals() and hashCode() methods will be the same.

4. Including Specific Fields

Now that we’ve learned how to exclude fields, let’s delve into including specific fields in the generation of the equals() and hashCode() methods.

4.1. Include at Field Level

To include specific fields when generating equals() and hashCode() methods, we can use the @EqualsAndHashCode.Include annotation. This annotation typically works in tandem with onlyExplicitlyIncluded=true on the @EqualsAndHashCode annotation:

@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Employee {
    @EqualsAndHashCode.Include
    private String name;
    @EqualsAndHashCode.Include
    private int id;
    private int age;
}

We set onlyExplicitlyIncluded=true attribute and annotated name and id fields with @EqualsAndHashCode.Include. Lombok generates the equals() and hashCode() methods using only these fields. It excludes the age field since it wasn’t marked with @EqualsAndHashCode.Include.

4.2. Include at Method Level

Moreover, we can incorporate the results of custom methods into the equals() and hashCode() methods by annotating them with @EqualsAndHashCode.Include:

@EqualsAndHashCode
public class Employee {
    private String name;
    private int id;
    private int age;

    @EqualsAndHashCode.Include
    public boolean hasOddId() {
        return id % 2 != 0;
    }
}

Here, we have annotated the hasOddId() method with @EqualsAndHashCode.Include, indicating that Lombok should use the result of this method in addition to the fields when generating the equals() and hashCode() methods:

public class EmployeeDelomboked {

    //fields, equals method
    //standard getters and setters
    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        result = result * PRIME + this.getId();
        result = result * PRIME + this.getAge();
        result = result * PRIME + (this.hasOddId() ? 79 : 97);
        final Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        return result;
    }
}

We can see the hashCode() method includes the hasOddId() method.

4.3. Include at Class Level

@EqualsAndHashCode includes an attribute of to define the included fields. In this case, we don’t use any annotations in the fields or methods:

@EqualsAndHashCode(of = {"name", "id"})
public class Employee {
    private String name;
    private int id;
    private int age;
}

Here, we specified the fields name and id to include in the @EqualsAndHashCode annotation by using the of attribute. By doing so, Lombok will use only these fields to generate the equals() and hashCode() methods.

This approach is similar to using @EqualsAndHashCode.Include with onlyExplicitlyIncluded attribute. Lombok actually recommends using onlyExplicitlyIncluded instead. The of attribute is expected to be deprecated in the future.

5. EqualsAndHashCode and Inheritance

When a class extends another class, Lombok’s @EqualsAndHashCode generated methods don’t call the parent class’s equals() and hashCode() methods by default. However, we can include the parent’s class’s equals() and hashCode() in the generation of the child class’s equals() and hashCode() by setting the callSuper attribute to true:

@EqualsAndHashCode(callSuper = true)
public class Manager extends Employee {
    private String departmentName;
    private int uid;
}
public class ManagerDelomboked extends Employee {
    //fields
    //equals implementation

    public int hashCode() {
        final int PRIME = 59;
        int result = super.hashCode();
        result = result * PRIME + this.getUid();
        final Object $departmentName = this.getDepartmentName();
        result = result * PRIME + ($departmentName == null ? 43 : $departmentName.hashCode());
        return result;
    }
}

Here, we can see that the hashCode() method calls the super.hashCode() method.

6. Lombok @EqualsAndHashCode Configuration

To configure the behavior of @EqualsAndHashCode annotation, we need to create a lombok.config file in our project. This file contains configuration keys that can be used to modify the behavior of the generated equals() and hashCode() methods.

6.1. lombok.equalsAndHashCode.doNotUseGetters

lombok.equalsAndHashCode.doNotUseGetters = [true | false] (default: false)

The configuration key lombok.equalsAndHashCode.doNotUseGetters can be set to true or false (default false).

When set to true, Lombok will access fields directly instead of using getters (if available) when generating the equals() and hashCode() methods. However, if the annotation parameter doNotUseGetters is explicitly specified, it takes precedence over this setting.

6.2. lombok.equalsAndHashCode.callSuper

lombok.equalsAndHashCode.callSuper = [call | skip | warn] (default: warn)

The configuration key lombok.equalsAndHashCode.callSuper can be set to call, skip, or warn (default warn).

If set to call, Lombok will include calls to the superclass implementation of hashCode() and equals() when generating these methods for a subclass. If set to skip, no such calls are generated. The default behavior is like skip, but with an additional warning.

6.3. lombok.equalsAndHashCode.flagUsage

lombok.equalsAndHashCode.flagUsage = [warning | error] (default: not set)

Lombok will flag any usage of @EqualsAndHashCode as a warning or error if configured.

7. Advantages and Disadvantages of Using @EqualsAndHashCode Annotation

There are both advantages and disadvantages to using the @EqualsAndHashCode annotation. Let’s take a look at some of them.

7.1. Advantages

Lombok’s @EqualsAndHashCode annotation is a useful technique for simplifying the creation of the equals() and hashCode() methods. It provides customization options, such as excluding fields or using a different hash code algorithm.

7.2. Disadvantages

There are several disadvantages to using Lombok’s @EqualsAndHashCode annotation. First, it can generate unwanted hash code collisions when two objects have different field values but the same hash code.

Second, it may not be compatible with other libraries and frameworks that rely on traditional implementations of equals() and hashCode().

Lastly, it can reduce readability by generating methods that aren’t explicitly defined in the class, making it more difficult to understand the logic of the code.

8. Common Issues

When using Lombok’s @EqualsAndHashCode annotation on classes with bidirectional relationships, such as parent-child relationships, a java.lang.StackOverflowError might occur.

Let’s look at an example of how @EqualsAndHashCode can cause a problem:

@EqualsAndHashCode
public class Employee {
    private String name;
    private int id;
    private int age;
    private Manager manager;
}
@EqualsAndHashCode
public class Manager {
    private String name;
    private Employee assistantManager;
}

In this example, the Employee and Manager classes have a bidirectional relationship and use @EqualsAndHashCode. When an instance of Employee calls its hashCode() method, it will trigger a call to the Manager class’s hashCode() method, which will recursively call back to Employee‘s hashCode() method. This recursive loop will continue until the program runs out of stack space and throws an error.

To avoid this issue, we can use the exclude or onlyExplicitlyIncluded attributes of @EqualsAndHashCode to exclude one of the classes from the generation of the hashCode() and equals() methods. For example, we can exclude the manager field from the hashCode() calculation in the Employee class:

@EqualsAndHashCode(exclude = "manager")
public class EmployeeV2 {
    private String name;
    private int id;
    private int age;
    private Manager manager;
}

9. Conclusion

In this article, we’ve seen how the Lombok @EqualsAndHashCode annotation generates equals() and hashCode() methods. We’ve also explored how inclusion and exclusion on the field and class level can customize the generated methods.

Using the Lombok @EqualsAndHashCode annotation can save time and effort. However, we should be aware of potential issues such as hash code collisions, incompatibility with other libraries, and StackOverflowError in bidirectional relationships.

As usual, the code for the article can be found over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!