In this post under Lombok, I will explain with example the purpose and how to use “EqualsAndHashCode” annotation.
This annotation is applied at the class level only.
This annotation instructs Lombok to automatically generate “equals” and “hashCode” method.
When generating “equals” and “hashCode” method it considers all non-static and non-transient fields.
For our example we will use the “Person” class as shown below.
Person
package package11;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class Person {
private String firstName;
private String middleName;
private String lastName;
private int age;
public Person(String firstName, String middleName, String lastName, int age) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
}
}
As shown in the above code, “@EqualsAndHashCode” annotation is applied at the class level.
Below is the main class
Main class
package package11;
public class Example11 {
public static void main(String[] args) {
Person person1 = new Person("Elvis", "M", "Emmerson", 39);
Person person2 = new Person("Elvis", "M", "Emmerson", 39);
Person person3 = new Person("Ralph", "M", "Emmerson", 39);
System.out.println("person1 equals person2: " + person1.equals(person2));
System.out.println("person2 equals person3: " + person2.equals(person3));
}
}
Below is the output
Output
person1 equals person2: true
person2 equals person3: false
As you can see from the output “person1 equals person2” return true which is correct and “person2 equals person3” return false which is also correct.
In this way we can use lombok’s “EqualsAndHashCode” annotation.