If the objects I create are not used for comparisons such as list.contains(new Employee("MM"))
, and also if those objects will only be stored in List
s returned from a database such as List<Employee>employeeList = employeeService.getEmployeeList();
then do I need to override equals()
and hashCode()
in Employee
class?
No, you do not need to override .equals()
and .hashCode()
if you don't need a custom definition of equality. As long as you intend to treat every instance of your class as un-equal to other instances the defaults will work fine. You can store such objects in List
s and even in hash-based collections such as HashMap
s and HashSet
s - both classes have no problems with the default Object
notion of equivalence.
Furthermore for many classes you shouldn't override these methods. Many common design patterns will include classes that aren't intended to ever be equivalent, such as factories, singletons, and state machines. Defining a custom notion of equality for such classes can introduce strange bugs, or at a minimum simply be unnecessary boilerplate.
On the other hand value types, or classes intended specifically to be a structured representation of some sort of data should almost always override .equals()
and .hashCode()
(and possibly implement Comparable
as well), because it's what users of these sort of classes are likely to expect. The Auto/Value project makes creating such value types really painless; if that's the type of class you're constructing I'd strongly encourage you to use it.
If you know you will never be using the object as a key in a HashMap
or will never be putting it in any sort of Set
, or never doing anything with it where you will do any object comparison other than "are these references referring to literally same instance or not", then you do not have to override equals()
and hashCode()
.
And if that's not the case and you do have to override them, then do consider letting your IDE generate the overrides rather than doing it manually -- especially for hashCode()
. And be aware that when having the IDE generate these, you can tell the IDE which fields to include and which fields not to include, which even further reduces any need to write the overrides manually.
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