Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding equals method in DTO's

Tags:

java

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.

like image 575
Harshana Avatar asked Aug 31 '11 05:08

Harshana


People also ask

Can we override equals method?

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.

Why is it needed to override equals () method in each DTO class?

Because DTO's are just use for transfer data.

What is the need for overriding equals () method in Java?

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.

What are equals () and hashCode () overriding rules?

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.


2 Answers

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.

like image 89
djna Avatar answered Sep 19 '22 14:09

djna


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.

like image 38
samitgaur Avatar answered Sep 19 '22 14:09

samitgaur