Is it necessary to override equals and hashcode methods in DTO's? Because DTO's are just use for transfer data. Is there any best practice or something regarding this?
Thanks.
You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.
Because DTO's are just use for transfer data.
Why we override equals() method? It needs to be overridden if we want to check the objects based on the property. For example, we want to check the equality of employee object by the id. Then, we need to override the equals() method.
if a class overrides equals, it must override hashCode. when they are both overridden, equals and hashCode must use the same set of fields. if two objects are equal, then their hashCode values must be equal as well. if the object is immutable, then hashCode is a candidate for caching and lazy initialization.
This article offers one piece of advice:
Objects placed in a List , Set, or Map (as either a key or value) should have an appropriate definition of equals.
Surely DTOs are used for more than just transfer, we do keep them, sort them, cache them ...
In practice do folks provide equals and hash? No not always. Should we? I think so.
Whether or not you need to provide equals
and hashcode
implementations for your DTO classes depends on how you use them.
If you use them with one or more Collections, you should provide the implementation for the appropriate method. Almost all Collections call equals
on the objects they store. Hash table based Collections like HashSet
and HashMap
call hashcode
, whereas sorted Collections like TreeSet
and TreeMap
call compareTo
method in addition to equals
.
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