Java Programming Handbook

    Understanding Set Interface in Java

    The Set interface in Java is part of the Java Collection Framework (JCF) and is used to store a collection of unique elements. Unlike lists, sets do not allow duplicate elements. Sets are commonly used when you need to eliminate duplicates or check membership efficiently.

    In this blog, we will explore the Set interface, its key methods, and its implementations: HashSet, LinkedHashSet, TreeSet, and SortedSet.

    What is the Set Interface?#

    The Set interface is present in the java.util package and extends the Collection interface.

    public interface Set<E> extends Collection<E> { // No new methods, inherits methods from Collection }

    Key Features of Set#

    • No Duplicate Elements: A set cannot contain duplicate values.
    • No Guarantee of Order (depends on the implementation).
    • Efficient Membership Tests: Checking whether an element exists is faster compared to lists.
    • Implements Collection Interface but adds the constraint of uniqueness.

    Key Methods of Set Interface#

    Since Set extends Collection, it inherits its methods. Some commonly used ones include:

    MethodDescription
    add(E e)Adds an element to the set. Returns false if the element already exists.
    remove(Object o)Removes the specified element from the set.
    contains(Object o)Checks if the set contains the specified element.
    size()Returns the number of elements in the set.
    clear()Removes all elements from the set.

    Implementations of Set Interface

    1. HashSet (Unordered & Fast)#

    Characteristics:#

    • Uses a HashTable internally.
    • No guarantee of insertion order.
    • Allows null values.
    • Fast access (O(1) time complexity for add, remove, and contains).

    Example:#

    import java.util.*; public class HashSetExample { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Mango"); set.add("Banana"); // Duplicate, will be ignored System.out.println("HashSet: " + set); } }

    Output:

    HashSet: [Apple, Banana, Mango]

    Note: Order may vary since HashSet does not maintain insertion order.

    2. LinkedHashSet (Ordered & Fast)#

    Characteristics:#

    • Extends HashSet but maintains insertion order.
    • Uses a doubly linked list alongside a HashTable.
    • Faster than TreeSet but slower than HashSet.

    Example:#

    import java.util.*; public class LinkedHashSetExample { public static void main(String[] args) { Set<String> set = new LinkedHashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Mango"); System.out.println("LinkedHashSet: " + set); } }

    Output:

    LinkedHashSet: [Apple, Banana, Mango]

    Note: The order of elements remains the same as insertion order.

    3. TreeSet (Sorted Order)#

    Characteristics:#

    • Implements SortedSet interface.
    • Maintains elements in sorted (ascending) order.
    • Uses a Red-Black Tree (Self-balancing BST).
    • Slower than HashSet but allows sorted retrieval.

    Example:#

    import java.util.*; public class TreeSetExample { public static void main(String[] args) { Set<Integer> set = new TreeSet<>(); set.add(30); set.add(10); set.add(20); System.out.println("TreeSet: " + set); } }

    Output:

    TreeSet: [10, 20, 30]

    Note: Elements are sorted in ascending order.

    4. SortedSet Interface (Extended Functionality of Set)#

    Additional Methods in SortedSet#

    MethodDescription
    first()Returns the first (lowest) element in the set.
    last()Returns the last (highest) element in the set.
    headSet(E toElement)Returns elements strictly less than toElement.
    tailSet(E fromElement)Returns elements greater than or equal to fromElement.

    Example:#

    import java.util.*; public class SortedSetExample { public static void main(String[] args) { SortedSet<Integer> set = new TreeSet<>(); set.add(50); set.add(20); set.add(30); System.out.println("First Element: " + set.first()); System.out.println("Last Element: " + set.last()); } }

    Output:

    First Element: 20 Last Element: 50

    Choosing the Right Set Implementation#

    FeatureHashSetLinkedHashSetTreeSet
    Order Maintained?NoYes (Insertion Order)Yes (Sorted Order)
    Speed (Add/Delete/Search)FastestFastSlowest (Balanced Tree)
    Allows null?YesYesNo
    Internal StructureHashTableHashTable + Linked ListRed-Black Tree
    Duplicate HandlingNot AllowedNot AllowedNot Allowed

    Conclusion#

    In this blog, we explored the Set interface and its implementations: HashSet, LinkedHashSet, TreeSet, and SortedSet.

    • Use HashSet when fast lookup is required, and ordering is not important.
    • Use LinkedHashSet when maintaining insertion order is needed.
    • Use TreeSet when sorting is necessary but at the cost of performance.

    In the next blog, we will explore all its implementations in detail .

    Last updated on Apr 09, 2025