Possible Duplicate:
Java: Always override equals?
should I override equals function for any class that I create?
even for very simple classes which only contains some very simple attributes and by equals I need every single attribute of it to be equal?
Override
equalsif (and only if) the object “represents some data”, i.e. if it models something such asPerson,CarorRecipieIngredient(these typically end up in collections etc). Don’t override equals for other types of classes, for exampleLoginServletorDatabaseUtil.Remember to always override
hashCodewhenever you overrideequals.Any two objects will be considered unequal unless they are the exact same object.
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(andhashCode) when implementing your own.Related questions: