📘 Lesson · Lesson 40
HashSet vs TreeSet
Two Set Types
Both store unique values, but HashSet is unordered (fast) and TreeSet is sorted (slower).
Comparison
| HashSet | TreeSet |
|---|---|
| no order | sorted order |
| faster (O(1)) | slower (O(log n)) |
| allows one null | no 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 (धीमा) है।
तुलना
| HashSet | TreeSet |
|---|---|
| no order | sorted order |
| तेज़ (O(1)) | धीमा (O(log n)) |
| एक null allowed | 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]
सारांश
- HashSet = unordered, सबसे तेज़; TreeSet = अपने आप sorted।
- Sorted unique values चाहिए तो TreeSet use करें।
💻 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.