ComparisonDifficulty: Intermediate1 min

HashSet, LinkedHashSet and TreeSet: Three Orderings, Three Costs

Three classes implementing Set, identical in what they promise and different in one thing the interface does not mention: what order you get things back in.

The three sets on iteration order, cost and what they require of elements
ClassIterates inAdd and containsRequires of elements
HashSetNo promised order at allConstanthashCode and equals
LinkedHashSetThe order you added themConstant, plus two pointers eachhashCode and equals
TreeSetSortedProportional to the logarithm of the sizeComparable, or a Comparator
java
for (Set<String> s : List.of(new HashSet<String>(), new LinkedHashSet<String>(), new TreeSet<String>())) {
    s.addAll(List.of("pear", "apple", "fig"));
    System.out.println(s);
}
text
[apple, pear, fig]
[pear, apple, fig]
[apple, fig, pear]

The decision rule. Use HashSet unless you need an order. Use LinkedHashSet when output should be reproducible or should match input order. Use TreeSet when you need the elements sorted, or need the extra questions a sorted set can answer — first, last, headSet, ceiling.