Member-only story

Effective Java! Obey the equals contract

Kyle Carter
7 min readDec 26, 2020

Today we are starting a new chapter. This new chapter covers methods common to all objects. And what are methods that are common to all objects? Well since every object eventually inherits from Object it would be methods on that object. The method we have a pleasure to talk about today is the equals method.

The equals method seems simple to override but it is actually easy to get ourselves into trouble with it as Effective Java details. So why must we override the equals method? Well actually we don't have to. If your class fulfills any of the following requirement there is no need to override the equals method:

  • Each instance of a class is inherently unique. Thread for example doesn't make sense to have two instances be equals.
  • If there is no desire for two objects of the type to be compared. This does seem risky in that if others are consuming your class you can’t know for sure if they will ever want to compare two instances of the class.
  • The superclass implements an equals method that is appropriate for the class. Examples of this are the implementation of equals in AbstractList thus none needed in ArrayList.
  • If the class is private or package-private and you can be sure that equals will never be called on the class.
  • If the class uses instance control. This is something like the singleton model we talked about in a previous item or enums where there is only a single instance. In these cases logical equality is…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

Responses (1)