Generating equals() and hashCode() is simple thing and IDE's help to generate them easily. But when time pass there may be more new fields getting add to Objects. When complexity of the project goes higher(Number of Object use in the code goes higher) that may become more complex to generate equals() and hashCode() time to time.
The moment add new fields to bean that person must regenerate equals() and hashCode() method again. If some one forgot to regenerate this will cause a failure.
I was unable to find a way to update equals() and hashCode() automatically at the moment add a new field. I found some interesting way with apache.commons.builder
Now we can override equals() and hashCode() in following way.
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
Now adding a new field not an issue to use this same equals() and hashCode().
Now my question, Is there better way to do this. Again this way we can use toString() method too.
The equals and hashCode methods are called too many times, for example , in many of the collections. My vote will be to avoid the use of reflection in above methods.
Guava has another approach to this. AutoValue Quote
AutoValue provides an easier way to create immutable value classes, with a lot less code and less room for error, while not restricting your freedom to code almost any aspect of your class exactly the way you want it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With