Grokking Java Interview Questions
Vote

0% completed

​

The equals and hashCode Contract

What is the difference between == and equals()?

What does the equals contract require?

How do you write hashCode() for a class?

Should equals() use getClass() or instanceof?

Predict the Output

Key Takeaways

The variables a and b refer to two separate objects of a class Product, and both objects have the name apple. Java can be asked in several ways whether they are the same product:

  • a == b is false, whatever the class contains.
  • a.equals(b) is false if the class does not override equals(), and it can be true if the class does.
  • List.of(a).contains(b) returns the result of b.equals(a).
  • new HashSet<>(List.of(a)).contains(b) depends on equals() and on hashCode() together.

The first answer is fixed by the language, and the class decides the other three. The sections below explain how the two methods define equality, which rules they must follow, and where inheritance makes those rules difficult.

What is the difference between == and equals()?

Level: Junior

The operator == compares two references, while equals() is a method that a class can define to compare the contents of two objects. Two references are equal when they identify the same object, which is called identity. Two different objects can be equal when the class says that their contents match.

The class Object declares equals(), and every class inherits it. The inherited version returns this == other, so a class that neither overrides the method nor inherits an override has no equality other than identity. String, the wrapper classes, records, lists, sets, and maps override it.

The program below creates two objects with the same name, first with a class that does not override equals() and then with a class that does. Each line prints ==, equals(), and List.contains().

Java
Java

. . . .
plain: false false false with equals: false true true

The operator gives the same result on both lines, because each new creates a separate object. The method contains() calls equals(), so it finds the second object only when the class defines equality.

Common mistake: Saying that equals() always compares contents. It compares whatever the class implements, and without an override it compares references.

Follow-up questions

1. Does equals() compare the elements of two arrays?

<details><summary>Show answer</summary>

No, an array inherits equals() from Object, so it compares references. The method Arrays.equals(a, b) compares the elements of two arrays. For an array that contains arrays, Arrays.deepEquals() also compares the inner elements.

</details>

2. How do you compare two objects when either variable can be null?

<details><summary>Show answer</summary>

The method Objects.equals(a, b) handles null on both sides. It returns true when both references are equal, which includes two null values. It returns false when only the first is null, and it calls a.equals(b) otherwise. A direct call to a.equals(b) throws NullPointerException when a is null.

</details>

What does the equals contract require?

Level: Mid-level

The documentation of Object.equals() requires five properties: reflexive, symmetric, transitive, consistent, and false for null. These rules are called a contract, because other code relies on them without checking. The compiler does not check them either.

For any references x, y, and z that are not null:

PropertyRequirement
Reflexivex.equals(x) is true
Symmetricx.equals(y) and y.equals(x) give the same result
TransitiveIf x equals y and y equals z, then x equals z
ConsistentRepeated calls give the same result while the compared data does not change
Nullx.equals(null) is false

Symmetry can be broken by accident when a subclass adds a field to the comparison. Suppose Product compares names, and DiscountedProduct extends it and also compares a discount percentage. The plain product apple ignores the discount, so apple.equals(sale) is true. The method of sale requires another DiscountedProduct, so sale.equals(apple) is false.

Java
Java

. . . .
apple.equals(sale): true sale.equals(apple): false list of apple contains sale: false list of sale contains apple: true

The last two lines show the damage. ArrayList.contains(x) calls x.equals(element), so the answer depends on which object is in the list and which one is the argument.

apple is a Product and sale is a DiscountedProduct. apple.equals(sale) compares only the names and returns true. sale.equals(apple) requires a DiscountedProduct and returns false.
apple is a Product and sale is a DiscountedProduct. apple.equals(sale) compares only the names and returns true. sale.equals(apple) requires a DiscountedProduct and returns false.

Look at the two directions. Each method applies the rule of its own class, and the two rules disagree about the same pair of objects.

Common mistake: Repairing the failure by ignoring the discount when the other object is a plain Product. The comparison becomes symmetric, but it is no longer transitive, as the exercise at the end of this lesson shows.

Follow-up questions

1. Does an equals() method need an explicit check for null?

<details><summary>Show answer</summary>

Not when it uses instanceof, because null instanceof Product is false. The same test handles objects of unrelated types, for which equals() should also return false instead of throwing. A method that calls other.getClass() needs the check, because that call throws for null.

</details>

2. Which JDK class has an equals() method whose result can depend on the network?

<details><summary>Show answer</summary>

The class java.net.URL compares host names by resolving them to IP addresses. Its Javadoc says that this is a blocking operation, and that the names are compared as text when one of them cannot be resolved. Two URL objects can therefore be different while the network is down and equal later, although their text is the same. The class java.net.URI compares the parts of its text and resolves no names.

</details>

How do you write hashCode() for a class?

Level: Mid-level

Combine the hash codes of the same fields that equals() compares, usually by multiplying by 31 at each step. A hash code is an int that summarizes an object, and hash tables use it to choose where to store and find the object. The contract demands one thing above all: equal objects must return equal hash codes.

The reverse is not required. Unequal objects may have the same hash code, because many classes have more possible values than an int has. The lesson How HashMap Stores and Finds Entries shows how a map separates such keys.

For a product with a name and a price, the calculation has two steps:

  1. Start with the hash code of the name, which is 93029210 for "apple".
  2. Multiply by 31 and add the price: 31 * 93029210 + 120. The sum does not fit in an int, so it wraps to -1411061666, which is harmless here.

The method Objects.hash(name, price) performs a similar calculation that starts from 1. It is shorter to write, but its parameter is a varargs array of objects. Each call creates an array and boxes the primitive values. A class whose hash code is computed very often can write the two steps directly.

Java
Java

. . . .
apple hash: 93029210 by hand: -1411061666 Objects.hash: -1411060705 sums: 165 and 165 with 31: 3765 and 1515

The two methods return different numbers because of the different start, and either one is valid as long as the class uses it everywhere. The last two lines combine the prices 120 and 45 in both orders. A plain sum cannot separate the two orders, while the multiplication by 31 can.

Left, valid: equals compares name and price, and hashCode uses name and price. Right, broken: equals compares only name and hashCode also uses price, so equal objects can have different hash codes.
Left, valid: equals compares name and price, and hashCode uses name and price. Right, broken: equals compares only name and hashCode also uses price, so equal objects can have different hash codes.

Notice the price field on the right. Two products with the name apple and different prices are equal there, yet their hash codes differ, so a HashSet can store both.

Common mistake: Overriding equals() without hashCode(). The class then inherits the version from Object, which typically returns different values for two equal objects.

Follow-up questions

1. Why is the multiplier 31 and not an even number?

<details><summary>Show answer</summary>

A multiplication by an even number moves information out of the 32 bits and loses it. Multiplying by 2 shifts every bit one place to the left, so the highest bit disappears, and 32 such steps remove a field from the result completely. An odd multiplier loses nothing. The value 31 is a convention that String, List, and Arrays follow.

</details>

2. May hashCode() use fewer fields than equals()?

<details><summary>Show answer</summary>

Yes, because equal objects still return equal hash codes. Objects that differ only in an omitted field share a hash code, which leads to more comparisons in a hash table. The opposite is an error: hashCode() must not use a field that equals() ignores.

</details>

Should equals() use getClass() or instanceof?

Level: Senior

Use instanceof when a subclass object may equal a superclass object, and getClass() when only objects of exactly the same class may be equal. The expression other instanceof Product accepts subclasses. The expression getClass() == other.getClass() rejects every object whose class is different, including a subclass.

Each choice gives something up. With getClass(), the comparison stays symmetric even when a subclass adds fields. However, it also rejects a subclass that adds nothing. This conflicts with the idea that a subclass object can be used wherever a superclass object is expected, which is called substitutability. With instanceof, such subclasses work, but the contract holds only if no subclass changes the comparison. Declaring the class or the equals() method final guarantees that.

The program below tests a subclass that adds no fields.

Java
Java

. . . .
instanceof: set contains the subclass object: true getClass: set contains the subclass object: false ArrayList equals LinkedList: true

The second line is a problem in practice. Some frameworks create a subclass of your class while the program runs and use its object in place of yours, which is called a proxy. A getClass() check treats the proxy of a product as a different product. An equals() method for such a class should also read the other object through its methods, since the fields of a proxy can be unset.

The last line needs instanceof as well: the List interface defines equality by the elements, so any two lists can be equal.

ClassSuitable check
final class or recordinstanceof, since no subclass exists
Class that frameworks extend with proxiesinstanceof, since the proxy is an object of a subclass
Open class whose subclasses add compared fieldsgetClass()

Common mistake: Claiming that instanceof always breaks symmetry. The check other instanceof Product in the class Product stays symmetric until a subclass overrides equals() with a different rule.

Follow-up questions

1. Why do records avoid this decision?

<details><summary>Show answer</summary>

A record class is implicitly final, so no subclass of it can exist. The compiler also generates equals() and hashCode() from all the components, so the two methods use the same fields unless the record declares its own version of one of them. A component of an array type is still compared by reference.

</details>

2. How can a class add a compared field without breaking the contract?

<details><summary>Show answer</summary>

It can hold the other object in a field instead of extending its class. A DiscountedProduct with a Product field and a percentage is not a Product, so the two types are never equal to each other. Its equals() method compares both fields. A method that returns the inner product serves code that needs one.

</details>

Predict the Output

The class DiscountedProduct below ignores the discount when it is compared with a plain Product. Write down the five lines, and decide which rule of the contract is broken.

Java
Java

. . . .
<details><summary>Show answer</summary>

The program prints true true, true, false, true, and false. The objects a and b are equal in both directions, because the discount is ignored, so symmetry holds. The objects b and c are equal for the same reason. The objects a and c are both discounted, so their percentages 10 and 25 are compared, and they differ. Transitivity is therefore broken. The hash codes of a and c are equal, since both come from the name, and unequal objects may share a hash code. In the last line, both instanceof tests are false for null.

</details>

Key Takeaways

  • == compares references, and equals() compares contents only when the class or a superclass overrides it to do so.
  • The contract requires a comparison that is reflexive, symmetric, transitive, consistent, and false for null.
  • A subclass that adds a compared field breaks symmetry or transitivity when equals() uses instanceof.
  • Equal objects must return equal hash codes, so hashCode() uses only fields that equals() compares.
  • Objects.hash() is convenient, and it creates an array on each call.
  • instanceof accepts objects of a subclass, such as proxies, and getClass() accepts only objects of the same class.

The class String follows this contract, and yet comparing two strings with == sometimes returns true. The lesson Strings, the String Pool, and Immutability explains when two strings are one object.

Reading Progress

0%


Vote for new content

On This Page

What is the difference between == and equals()?

What does the equals contract require?

How do you write hashCode() for a class?

Should equals() use getClass() or instanceof?

Predict the Output

Key Takeaways