Equality of Objects in Java

yongjoon
2 min readNov 26, 2023

One developer said programming is all about if-else. So we are comparing values all the time. But do we know equality well? What is equality in the first place?

First of all, we need to define the meaning of equality in Java. Aren’t they just objects with the same value or something? not quite. In Java, I can think of three kinds of equalities.

  • Reference Equality: Do two objects share the same memory?
  • Object Equality: Do two objects have the same property values?
  • Context Equality: Do two objects have the same context regardless of properties?

I don’t want to dive deep into Reference and Object Equality in this post. But I want to talk about Context Equality more.

Context Equality is special equality, and I just named it. Sometimes two objects should be treated as the same even though they have different property values. For example, there are BigDecimal and ZonedDateTime in Java.

BigDecimal Context Equality

var n1 = new BigDecimal("2.00");
var n2 = new BigDecimal("2");
n1.equals(n2) // false => Object Equality
n1.compareTo(n2) // 0 (equal) => Context Equality

ZonedDateTime Context Equality

var utcNow = ZonedDateTime.now(ZoneId.of("UTC"));
var kstNow = utcNow.withZoneSameInstant(ZoneId.of("UTC+9"));
utcNow.equals(kstNow) // false => Object Equality
utcNow.isEqual(kstNow) // true => Context Equality

We should be careful when we deal with objects that can be compared by their context, like the two.

If you use Lombok, you can easily generate equals of custom objects using annotations like EqualsAndHashCode. This generates an equals method with Object Equality of all properties. So BigDecimal and ZonedDateTime properties might return false on equals of your custom objects. If you want to use Context Equality, then you need to find another way of implementing the equality method.

It still is hard to find when you are using the wrong equality. For example, you might be using Object Equality on BigDecimal, but you actually thought you were using Context Equality. You might have several test cases for your business logic. How likely can those tests detect that you are using the wrong equality? Do you usually write, “Oh, I need to test 2.00 and 2 with two BigDecimal because I might accidentally use Object Equality!” I don’t think so. Most of us likely compare two 200 and 200 and are satisfied that the test passes green.

So If you are dealing with objects that have some contexts, think once, “Am I using Context Equality or Object Equality in my logic?” This simple question could reduce hours of finding bugs and fixing them later.

If you want to read more about equality in programming, I recommend reading below.

--

--

yongjoon

Hi, I'm yongjoon, a backend developer passionate about creating content and solving tech challenges. Empowering devs to learn and grow!