sawyinwaimon sawyinwaimon - 1 year ago 76
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
s returned from a database such as
List<Employee>employeeList = employeeService.getEmployeeList();
then do I need to override

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download