Search code examples
javaequalshashcode

Java: Automatic equals() and hashCode()


Implementing equals() and hashCode() for simple data POJOs is cluttering my code and maintaining is tedious.

What are the libraries handling this automatically?
I prefer bytecode instrumentation over AOP approach due to performance reasons.

Update: The topic of the necessity of implementing equals() and hashCode() has been discussed, here's my point:

Isn't it better to have it done right upfront with minimal effort rather than digging in the code, adding hC/eq when it comes to it?

Edit 2022: I have switched to Kotlin. Kotlin takes care of most of Java's boilerplate, see this page for the case of equals(): https://tedblob.com/kotlin-data-class/


Solution

  • Project Lombok provides the annotation @EqualsAndHashCode which will generate equals() and hashCode() for your Java classes. Of course there are some drawbacks in comparison to manually implementing these methods, so make sure you read the "small print" on the linked page.