← Back to Java

HashSet vs TreeSet

JavaMiddata-structuresjava

The Question

What is the difference between HashSet and TreeSet?

What a Strong Answer Covers

  • HashSet backed by HashMap O(1) unordered allows null
  • TreeSet backed by TreeMap O(log n) sorted no null
  • HashSet uses hashCode/equals
  • TreeSet uses compareTo/Comparator

Senior-Level Answer

HashSet and TreeSet are both implementations of the Set interface in Java, but they differ fundamentally in their underlying data structures, performance characteristics, and ordering guarantees.

HashSet is backed by a HashMap internally. When you add an element, it computes the hash code, determines the bucket, and stores the element as a key in the underlying map. This gives HashSet O(1) average-case time complexity for add, remove, and contains operations. However, HashSet provides no ordering guarantees — iterating over a HashSet may return elements in any order. HashSet allows one null element and requires that elements properly implement hashCode() and equals().

TreeSet is backed by a TreeMap, which uses a red-black tree — a self-balancing binary search tree. This gives TreeSet O(log n) time complexity for add, remove, and contains operations. The key advantage is that TreeSet maintains elements in sorted order, either by natural ordering (Comparable) or by a custom Comparator. TreeSet does not allow null elements because it needs to compare every element.

Because TreeSet implements NavigableSet, it exposes powerful methods: first(), last(), headSet(), tailSet(), subSet(), ceiling(), floor(), higher(), and lower(). These allow efficient range queries that would require sorting the entire collection with a HashSet.

When choosing between them, use HashSet when you need fast lookups and do not care about ordering. Use TreeSet when you need sorted order or range queries. One subtle point: TreeSet's ordering must be consistent with equals. If a Comparator considers two distinct objects as equal (returns 0), TreeSet will reject the second one, even if equals() returns false.

Key Differences

AspectHashSetTreeSet
Underlying structureHashMap (hash table)TreeMap (red-black tree)
Time complexityO(1) averageO(log n) guaranteed
OrderingNo ordering guaranteeSorted (natural or Comparator)
Null elementsAllows one nullDoes not allow null
InterfaceSetSet, SortedSet, NavigableSet
Range queriesNot supportedheadSet, tailSet, subSet, ceiling, floor
Key requirementhashCode() and equals()Comparable or Comparator

What Separates a 2/3 from a 3/3

2/3 — Passing but Incomplete

Identifies that HashSet is O(1) and unordered while TreeSet is O(log n) and sorted. Mentions underlying data structures. May not discuss NavigableSet methods.

3/3 — Strong Answer

Explains both data structures, contrasts time complexities, covers ordering guarantees, mentions NavigableSet methods like ceiling/floor/subSet, discusses null handling, and provides practical guidance on when to use each.

Common Mistakes

  • Saying TreeSet is O(n) instead of O(log n)
  • Forgetting that TreeSet does not allow null elements
  • Not mentioning NavigableSet and its range query methods
  • Claiming HashSet maintains insertion order — that is LinkedHashSet
  • Ignoring that TreeSet's Comparator must be consistent with equals

Follow-Up Questions

  • What happens if two objects are equal according to the Comparator but not according to equals() in a TreeSet? — TreeSet treats compareTo/compare returning 0 as equality — the second element is rejected.
  • When would you use a LinkedHashSet instead? — When you need O(1) operations but also want to preserve insertion order.
  • How does HashSet handle hash collisions? — Same as HashMap — linked lists that convert to balanced trees in Java 8+.
  • Can you make a TreeSet use descending order? — Use descendingSet(), Comparator.reverseOrder(), or Collections.reverseOrder().

Related Questions

  • JVM vs JRE vs JDK
  • Java Platform Independence
  • How JVM Works
  • Main Features of Java
  • public static void main

Can You Explain This Cold?

Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.

Get Graded — Free Assessment
GrindQuestionsAITechnical interview assessment
TermsPrivacyAbout