Using @EqualsAndHashCode.Exclude annotation

In this post under lombok, I will show with example the purpose of @EqualsAndHashCode.Exclude annotation.

In the previous post, I explained with example the purpose of “@EqualsAndHashCode” annotation.

It generates “equals” and “hashCode” method for the “@EqualsAndHashCode” annotated class.

When generating “equals” and “hashCode” method it takes into consideration all the fields of the class.

But sometimes due to some requirements we want to exclude certains fields from consideration when generating “equals” and “hashCode” method.

That’s where “@EqualsAndHashCode.Exclude” annotation comes into the picture.

This annotation is applied at the field level and it is used along with “@EqualsAndHashCode” annotation.

Below is the example that shows how to use these two annotations together in model class.

Person class

1  package package12;
3  import lombok.EqualsAndHashCode;
5  @EqualsAndHashCode
6  public class Person {
7      private String firstName;
8      private String middleName;
9      private String lastName;
10     @EqualsAndHashCode.Exclude
11     private int age;
13     public Person(String firstName, String middleName, String lastName, int age) {
14         this.firstName = firstName;
15         this.middleName = middleName;
16         this.lastName = lastName;
17         this.age = age;
18     }
19 }

In the above person class structure, as usual the class is annotated with “@EqualsAndHashCode” indicating lombok to generate “equals” and “hashCode” methods.

At line 10, we have added “@EqualsAndHashCode.Exclude” annotation to “age” field, this informs lombok to exclude the field when generating “equals” and “hashCode” methods.

Below is the main method for your reference

Main class

package package12;

public class Example12 {
    public static void main(String[] args) {
        Person person1 = new Person("Elvis", "M", "Emmerson", 39);
        Person person2 = new Person("Elvis", "M", "Emmerson", 30);

        System.out.println("person1 equals person2: " + person1.equals(person2));

In the above main method, I have created two “Person” object with same first, middle, and last name but different age.

When we compare them using “equals” method, the output will be true even though the age is different.

This is because we have told “equals” method not to check for “age” field.

In this way we can exclude certain fields from consideration when generating “equals” and “hashCode” methods.

Below is the output


    person1 equals person2: true

Leave a Reply