Card 03/ 08
All 8 cards
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.
| Class | Iterates in | Add and contains | Requires of elements |
|---|---|---|---|
HashSet | No promised order at all | Constant | hashCode and equals |
LinkedHashSet | The order you added them | Constant, plus two pointers each | hashCode and equals |
TreeSet | Sorted | Proportional to the logarithm of the size | Comparable, or a Comparator |
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);
}[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.
- Java
- Java Collections
- Performance