sawyinwaimon sawyinwaimon - 19 days ago 6
Java Question

Effective Java: should I override equals() and hashCode() if the objects I'm creating are never compared with each other?

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?

Answer

Why overriding Equals Method:

If you object needs to be stored on Collection i.e List, you should override equals method since when you will use indexOf, lastIndexOf etc API method as those api methods internally uses equals method. If you dont override equal method, then you might get those object back from collections since identity checking is not the right way to get the object back from Collections.

Why overriding hashCode Method:

If your object needs to be stored in a set or as key object in a map collection, you must override HashCode and Equals both becuase both methods are used to get the object back from those collections.

Comments