☕ Java Intermediate

What is the difference between HashSet and TreeSet?

Answer

HashSet stores elements using a HashMap internally. It offers O(1) average performance for add, remove, and contains operations but makes no guarantee about the order of elements — iteration order is unpredictable. TreeSet stores elements in a red-black tree, keeping them sorted in natural order (or by a provided Comparator). All basic operations are O(log n). TreeSet also provides useful navigation methods like first(), last(), headSet(), and tailSet(). Use HashSet when you only care about uniqueness and fast lookups; use TreeSet when you need elements in sorted order or need range views of the set.