Java: When should I override equals?

Override equals (and hashCode) if and only if your class represents some form of value or entity.

Should override equals:
  • Complex
  • Person
  • Car
  • Word
  • Command
Should not override equals:
  • EntityManager
  • ExecutionHelper
  • SuccessCallback
  • DatabaseUtil
  • LoginServlet

Regarding Mutable classes

It is often good practice to make classes representing values and entities immutable. (What exactly is immutable?) If this is not an option in your situation, think twice before overriding equals. Imagine what could happen if the equality of two objects changes between the point where equals is called, and the point where the code actually relies value returned by the equals call. As a concrete example, using mutable objects (with custom equals/hashCode implementations) as keys in hash maps is a big no no!

Remember to also override hashCode!

Why should I always override hashCode when overriding equals?

Comments

Be the first to comment!