Java.Collections.What is the difference between TreeSet and HashSet?

🌳 vs 🧩 — TreeSet and HashSet are both implementations of the Set interface in Java, but they have very different behaviors under the hood.

Let’s compare them clearly and concisely:


1. Ordering

FeatureHashSetTreeSet
Ordering❌ No ordering — elements are unordered✅ Sorted according to natural order or a custom Comparator
Example[banana, apple, orange] (random)[apple, banana, orange] (sorted)

2. Performance (Time Complexity)

OperationHashSet (backed by HashMap)TreeSet (backed by TreeMap)
add, remove, containsO(1) average caseO(log n)
  • HashSet is faster on average.
  • TreeSet trades speed for sorted order.

3. Null elements

FeatureHashSetTreeSet
Null allowed?✅ Yes (only one null)⚠️ Only if null is comparable — otherwise throws NullPointerException

4. Underlying data structure

Set TypeInternally uses
HashSetHashMap (buckets)
TreeSetTreeMap (Red-Black Tree)

5. Use case difference

Use CaseChoose…
Fast insertion/lookup, no orderHashSet
Keep elements sortedTreeSet
Need range queries (e.g. headSet(), tailSet())TreeSet

🔥 Code Comparison

Set<String> hashSet = new HashSet<>();
hashSet.add("banana");
hashSet.add("apple");
hashSet.add("orange");
System.out.println(hashSet); // Unpredictable order

Set<String> treeSet = new TreeSet<>();
treeSet.add("banana");
treeSet.add("apple");
treeSet.add("orange");
System.out.println(treeSet); // [apple, banana, orange]

🧠 TL;DR

FeatureHashSetTreeSet
Order❌ None✅ Sorted
Speed⚡ Fast (O(1))🕗 Slower (O(log n))
Nulls allowed✅ One⚠️ Careful — may throw
Backing structureHashMapTreeMap
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.