toString(), equals() and hashCode() method with Project Lombok

In many situations working with Java object, we need define toString(), equals() or hashCode() method. These methods can be added to the Java object automatically by using Project Lombok. In this tutorial, I will show you all about this!

First of all, we need a Maven project for example:

toString(), equals() and hashCode() method with Project Lombok

with Project Lombok dependency as below:

Remember that, we need install Project Lombok plugin into our IDE. See construction for IntelliJ IDEA at here.

Now, for example, I have a Student class with some information like name, code, dateOfBirth. Without using Lombok library, I must declare the method toString(), equals() and hashCode() method (other Getter, Setter methods or constructors, I defined with Project Lombok) like below:

We can automate this by using @ToString and @EqualsAndHashCode annotation as below:

  • @ToString: will generate toString() method with all class fields. We no need to maintain this method when we add more and remove some fields.
  • @EqualsAndHashCode: this annotation will help Project Lombok generate the method equals() and hashCode() with all class nonstatic and nontransient fields automatically.

Now, if you check in the folder /target/classes/com/huongdanjava/lombok, the content of Student.class will be as below:

You can see, because the field code in Student bean was declared as the transient field, then in generated equals() and hashCode() method, we didn’t see it included.

Now, if we have 2 Student objects with different codes, same name and dateOfBirth, when comparing, you will still see the same. For example:

Result:

toString(), equals() and hashCode() method with Project Lombok

You can exclude some fields which we don’t want to include in toString(), equals() and hashCode() method by declaring exclude attribute in @ToString and @EqualsAndHashCode annotation.

For example, now, I want to exclude dateOfBirth field in Student bean, I will declare as below:

Now, if you check in the folder /target/classes/com/huongdanjava/lombok, the content of Student.class will be as below:

5/5 - (1 vote)

One thought on “toString(), equals() and hashCode() method with Project Lombok

Add Comment