Command Palette

Search for a command to run...

Back to the lesson: Topic 9.5 — HashSet, LinkedHashSet and TreeSet
Core Java · Example 4 of 4

When compareTo and equals disagree

HashSet asks equals (scale matters); TreeSet asks compareTo (only the value matters).

A Set holds each element at most once. HashSet is a HashMap with only keys (O(1), no order), LinkedHashSet adds insertion order, and TreeSet keeps elements sorted in a red-black tree (O(log n)) with navigation methods like floor and ceiling.

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

Remove duplicates from ["b", "a", "b", "c", "a"] keeping first-seen order, then print the distinct elements in sorted order too.

02

Given a sorted set of exam cut-off marks {40, 55, 70, 85} and grades D, C, B, A for each cut-off, print the grade for marks 39, 40, 69 and 99 using floor (below 40 is F). Use a TreeMap for the mapping.

03

Find the first repeated character in "programming" using a HashSet and the boolean returned by add.

Explain it without notes

01

How is HashSet implemented, and what does that imply for its element classes?

02

Compare HashSet, LinkedHashSet and TreeSet on order, complexity, nulls and requirements on elements.

03

What does it mean for a comparator to be inconsistent with equals, and why does it matter?

04

What is a red-black tree and why does TreeSet use one instead of a plain binary search tree?

When compareTo and equals disagree
Sign in to run this example in your browser.

Expected output

add Tea: true
add tea: false
drinks: [Tea], contains TEA? true
equals: false, compareTo: 0
HashSet size 2, TreeSet size 1 [1.0]