Command Palette

Search for a command to run...

Back to the lesson: Topic 4.8 — toString, equals and hashCode
Core Java · Example 2 of 4

Forget hashCode and HashSet breaks

With identity hashes, two equal NoHash objects (almost) never share a hash, so the set treats them as different.

Every class inherits toString, equals and hashCode from Object. Override toString to get readable output, and override equals and hashCode together, following their contract, whenever two different objects should count as "the same value", because HashMap, HashSet and most of the collections library depend on it.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a final class Money with long paise and String currency, plus correct equals, hashCode and toString. Show that two equal amounts are equals and that a HashSet keeps only one.

02

Write an equals for a class Book(String isbn, String title) where two books are equal if their ISBNs are equal (the title may be null). Show that the null title causes no exception.

03

Show the symmetry trap: a class CaseInsensitive wrapping a String whose equals also accepts plain Strings ignoring case. Print ci.equals("HELLO") and "HELLO".equals(ci) and explain the result.

Explain it without notes

01

What do the default toString, equals and hashCode in Object do?

02

State the five rules of the equals contract.

03

State the hashCode contract and explain exactly what goes wrong in a HashSet if you override equals without hashCode.

04

Why is equals(Point p) a bug, and how does @Override help?

05

Why shouldn't you mutate an object while it's a key in a HashMap?

Forget hashCode and HashSet breaks
Sign in to run this example in your browser.

Expected output

NoHash: equals says true
NoHash: set size 2, contains false
Good:   set size 1, contains true