Skip to main content
PreparationZone Logo
PrepZone

HashSet, LinkedHashSet and TreeSet

Three ways to guarantee uniqueness, differing only in ordering, cost and null handling.

Pass checkpoint below

Why this matters

  • A Set is the clearest way to express "membership matters, duplicates do not", and using a List with contains instead is a common and avoidable O(n) mistake.
  • Which set you pick determines whether iteration order is arbitrary, insertion-based or sorted, and that silently affects test reliability.
  • Uniqueness depends entirely on equals and hashCode, so a broken contract shows up here first.

Three implementations

HashSetNo order · O(1) · one null
LinkedHashSetInsertion order · O(1) · one null
TreeSetSorted · O(log n) · no null
All three reject duplicates. They differ only in the order you get back when iterating and in what that ordering costs.
AspectImplementationProperties
HashSetNo order guaranteeO(1) add, remove, contains
LinkedHashSetInsertion order preservedO(1), slightly more memory for the links
TreeSetSorted orderO(log n), plus navigation and range queries
  • HashSet

    ImplementationNo order guarantee
    PropertiesO(1) add, remove, contains
  • LinkedHashSet

    ImplementationInsertion order preserved
    PropertiesO(1), slightly more memory for the links
  • TreeSet

    ImplementationSorted order
    PropertiesO(log n), plus navigation and range queries

Each wraps a map internally: HashSet over HashMap, LinkedHashSet over LinkedHashMap, TreeSet over TreeMap.

Java
Loading compiler…

Each dropped the duplicate "ana". Only the ordering differs.

Uniqueness depends on your contract

A HashSet decides whether an element is already present by hashing it and then comparing with equals. A broken contract breaks the set.

Java
Loading compiler…
Java
Loading compiler…

TreeSet uses compareTo or a supplied Comparator instead, so it has the same dependency on a different method. Two elements comparing as 0 are considered duplicates even if equals disagrees.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 5 sections

  • TreeSet navigation
  • Set algebra
  • EnumSet for enum keys
  • Choosing
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.