📘 Lesson  ·  Lesson 40

HashSet vs TreeSet

Two Set Types

Both store unique values, but HashSet is unordered (fast) and TreeSet is sorted (slower).

Comparison

HashSetTreeSet
no ordersorted order
faster (O(1))slower (O(log n))
allows one nullno null

Example

TreeSet<Integer> ts = new TreeSet<>();
ts.add(5); ts.add(1); ts.add(3);
System.out.println(ts);   // [1, 3, 5] - sorted
[1, 3, 5]

Summary

  • HashSet = unordered, fastest; TreeSet = automatically sorted.
  • Use TreeSet when you need sorted unique values.

दो Set Types

दोनों unique values रखती हैं, पर HashSet unordered (तेज़) और TreeSet sorted (धीमा) है।

तुलना

HashSetTreeSet
no ordersorted order
तेज़ (O(1))धीमा (O(log n))
एक null allowednull नहीं

Example

TreeSet<Integer> ts = new TreeSet<>();
ts.add(5); ts.add(1); ts.add(3);
System.out.println(ts);   // [1, 3, 5] - sorted
[1, 3, 5]

सारांश

  • HashSet = unordered, सबसे तेज़; TreeSet = अपने आप sorted।
  • Sorted unique values चाहिए तो TreeSet use करें।
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.