What is the difference between HashSet, LinkedHashSet, and TreeSet?
7 minintermediatehashsetlinkedhashsettreeset
Quick Answer
HashSet offers O(1) average add/contains with no ordering guarantee. LinkedHashSet adds a linked list threading through entries to preserve insertion order, at a small memory/performance cost. TreeSet keeps elements sorted (via natural ordering or a Comparator) using a red-black tree, giving O(log n) operations and sorted iteration/range queries.
Detailed Answer
All three implement Set (no duplicates), backed by different underlying structures:
HashSet: backed by aHashMapinternally (elements stored as keys). O(1) averageadd/contains/remove, but iteration order is unspecified and can change across JVM versions or even between runs.LinkedHashSet: extendsHashSetbut additionally threads a doubly-linked list through all entries to remember insertion order — iteration order matches the order elements were added, at a modest extra memory cost (the links) and similar O(1) operation cost.TreeSet: implementsNavigableSet, backed by a red-black tree (TreeMapinternally). Elements are always kept in sorted order (natural ordering viaComparable, or a customComparatorpassed to the constructor). Operations are O(log n), and it supports range views (headSet,tailSet,subSet) and nearest-neighbor queries (floor,ceiling,higher,lower).
Set<String> hash = new HashSet<>(); // arbitrary iteration order
Set<String> linked = new LinkedHashSet<>(); // insertion order
Set<String> tree = new TreeSet<>(); // sorted order
Choosing: use HashSet by default for pure membership testing; LinkedHashSet when you need predictable, insertion-ordered iteration without paying for sorting; TreeSet when you need the elements sorted or need range/nearest queries, accepting the O(log n) cost and the requirement that elements be mutually comparable.