should I override equals function for any class that I create?
Override equals
if (and only if) the object “represents some data”, i.e. if it models something such as Person
, Car
or RecipieIngredient
(these typically end up in collections etc). Don’t override equals for other types of classes, for example LoginServlet
or DatabaseUtil
.
Remember to always override hashCode
whenever you override equals
.
(A natural follow-up question:) What happens if I don’t override equals and hashCode?
Any two objects will be considered unequal unless they are the exact same object.
[…] I need every single attribute of it to be equal?
Typically yes. It depends on how you define your notion of equality. Note that for reference types, you can reuse/delegate to that objects implementation of equals
(and hashCode
) when implementing your own.
Related questions: