In this post under Lombok, I will explain with example the purpose of “cacheStrategy” attribute of “@EqualsAndHashCode” annotation.
Just for recap, the annotation “@EqualsAndHashCode” when annotated to a POJO class, it generates “equals” and “hashCode” methods.
Whenever the “hashCode” method of a POJO class is called, the hash is computed.
To avoid computing of hashCode every time a call is made to “hashCode” method of a POJO class, we can cache the value.
That is where “cacheStrategy” attribute comes into picture.
By default the value of this attribute will be “NEVER”. Changing this value to anything other than “NEVER” will cache the computed hashcode.
Below is an example showing how to use it.
Person class
package package17;
import lombok.EqualsAndHashCode;
import lombok.EqualsAndHashCode.CacheStrategy;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@EqualsAndHashCode(cacheStrategy = CacheStrategy.LAZY)
public class Person {
private String firstName;
private String middleName;
private String lastName;
private float salary;
public Person(String firstName, String middleName, String lastName, float salary) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.salary = salary;
}
}
As you can see in the above code, The “cacheStrategy” attribute of “@EqualsAndHashCode” annotation is set to “LAZY”
As a result of which the hashCode is stored in cache.
In this way we can use “cacheStrategy” attribute.