JAVA - Zero to Hero / Collection Framework

Set Interface (HashSet, TreeSet)

🧺 Set Interface (HashSet, TreeSet)

The Set interface in Java is a part of the Collections Framework and represents a collection that does not allow duplicate elements. Unlike List, sets are unordered (in most implementations) and are mainly used to store unique values.


🧩 Key Features of Set Interface:

  • No duplicates allowed

  • At most one null element (depends on implementation)

  • Does not guarantee order (except in some implementations like TreeSet)

  • Backed by different data structures for different performance trade-offs


🔧 Implementations of Set

1. HashSet – Unordered, Fast Access

  • Based on a hash table

  • Does not maintain order

  • Allows one null element

  • Best for performance (O(1) for add, remove, contains)

✅ Example: HashSet

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();

        set.add("Apple");
        set.add("Banana");
        set.add("Mango");
        set.add("Banana");  // Duplicate, ignored

        System.out.println(set);
    }
}
[Mango, Banana, Apple]

Note: The output order may vary, because HashSet does not maintain insertion order.


2. TreeSet – Sorted Set

  • Based on a Red-Black Tree

  • Maintains elements in sorted (ascending) order

  • Does not allow null

  • Slower than HashSet (O(log n) for operations)

✅ Example: TreeSet

import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        TreeSet<Integer> numbers = new TreeSet<>();

        numbers.add(40);
        numbers.add(10);
        numbers.add(20);
        numbers.add(10);  // Duplicate, ignored

        System.out.println(numbers);
    }
}
[10, 20, 40]

The output is always sorted in ascending order.


⚖️ HashSet vs TreeSet

Feature

HashSet

TreeSet

Order

No guaranteed order

Sorted (natural order)

Null Elements

Allows one null

❌ No null elements

Performance

Faster (O(1))

Slower (O(log n))

Internal Structure

Hash Table

Red-Black Tree (Balanced BST)

Use Case

When order doesn't matter

When you need sorted elements


🧠 Common Methods in Set

Method

Description

add(elem)

Adds an element

remove(elem)

Removes an element

contains(elem)

Checks if element exists

size()

Returns number of elements

clear()

Removes all elements

isEmpty()

Checks if set is empty


✅ Real-world Use Cases

  • Storing unique usernames

  • Checking for duplicate entries

  • Keeping track of visited web pages

  • Implementing set operations (union, intersection)