Thursday, May 5, 2016

How to Implement Java’s equals Method Correctly

A fundamental aspect of any Java class is its definition of equality.
It is determined by a class's equals method and there are a couple of things to be considered for a correct implementation. Let's check 'em out so we get it right!

Note that implementing equals always means that hashCode has to be implemented as well! We'll cover that in a separate article so make sure to read it after this one.

Identity Versus Equality

Have a look at this piece of code:

String some = "some string";
String other = "other string";

We have two strings and they are obviously different.

What about these two?

String some = "some string";
String other = some;
boolean identical = some == other;

Here we have only one String instance and some and other both reference it.
In Java we say some and other are identical and, accordingly, identical is true.

[author_more]

What about this one?

String some = "some string";
String other = "some string";
boolean identical = some == other;

Now, some and other point to different instances and are no longer identical, so identical is false.
(We'll ignore String interning in this article; if this bugs you, assume every string literal were wrapped in a new String(...).)

But they do have some relationship as they both "have the same value".
In Java terms, they are equal, which is checked with equals:

String some = "some string";
String other = "some string";
boolean equal = some.equals(other);

Here, equals is true.

A variable's Identity (also called Reference Equality) is defined by the reference it holds.
If two variables hold the same reference they are identical.
This is checked with ==.

A variable's Equality is defined by the value it references.
If two variables reference the same value, they are equal.
This is checked with equals.

But what does "the same value" mean? It is, in fact, the implementation of equals that determines "sameness". The equals method is defined in Object and since all classes inherit from it, all have that method.

The implementation in Object checks identity (note that identical variables are equal as well), but many classes override it with something more suitable.
For strings, for example, it compares the character sequence and for dates it makes sure that both point to the same day.

Many data structures, most notably Java's own collection framework, use equals to check whether they contain an element.

For example:

List<String> list = Arrays.asList("a", "b", "c");
boolean contains = list.contains("b");

The variable contains is true because, while the instances of "b" are not identical, they are equal.

(This is also the point where hashCode comes into play.)

Continue reading %How to Implement Java’s equals Method Correctly%


by Nicolai Parlog via SitePoint

No comments:

Post a Comment