Three sets, same input
Integer's hashCode is its value, so small numbers land in buckets 1, 2, 3, 5, 6 in that order. With strings the HashSet order would look random.
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.
Remove duplicates from ["b", "a", "b", "c", "a"] keeping first-seen order, then print the distinct elements in sorted order too.
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.
Find the first repeated character in "programming" using a HashSet and the boolean returned by add.
Explain it without notes
How is HashSet implemented, and what does that imply for its element classes?
Compare HashSet, LinkedHashSet and TreeSet on order, complexity, nulls and requirements on elements.
What does it mean for a comparator to be inconsistent with equals, and why does it matter?
What is a red-black tree and why does TreeSet use one instead of a plain binary search tree?
Expected output
repeat roll: 6
repeat roll: 2
HashSet: [1, 2, 3, 5, 6] (small Integers happen to look sorted)
LinkedHashSet: [6, 2, 3, 1, 5]
TreeSet: [1, 2, 3, 5, 6]
contains 4? false, size 5