DEV Community

Sudhakar V
Sudhakar V

Posted on

Set Interface in Java

The Set interface in Java extends the Collection interface and represents an unordered collection of elements that does not allow duplicates. It is used when uniqueness of elements is required.

1. Key Implementations of Set

Class Description
HashSet Uses a hash table (fastest operations, no order).
LinkedHashSet Maintains insertion order (slower than HashSet).
TreeSet Stores elements in sorted order (uses Comparable or Comparator).

2. Set Interface Methods (Detailed)

📌 Basic Operations

Method Description Example
boolean add(E e) Adds an element if not already present. set.add("Java");
boolean remove(Object o) Removes the specified element. set.remove("Java");
int size() Returns the number of elements. int size = set.size();
boolean isEmpty() Checks if the set is empty. if (set.isEmpty()) {...}
void clear() Removes all elements. set.clear();
boolean contains(Object o) Checks if the element exists. if (set.contains("Java")) {...}

📌 Bulk Operations (Working with Multiple Elements)

Method Description Example
boolean addAll(Collection<? extends E> c) Adds all elements from another collection. set.addAll(otherSet);
boolean removeAll(Collection<?> c) Removes all elements present in the given collection. set.removeAll(toRemove);
boolean retainAll(Collection<?> c) Keeps only elements present in the given collection. set.retainAll(toKeep);

📌 Iteration & Conversion

Method Description Example
Iterator<E> iterator() Returns an iterator for sequential access. Iterator<String> it = set.iterator();
Object[] toArray() Converts the set to an array. Object[] arr = set.toArray();
<T> T[] toArray(T[] a) Converts the set to a typed array. String[] arr = set.toArray(new String[0]);

3. Example: Using Set Methods

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        Set<String> languages = new HashSet<>();

        // 1. Adding elements
        languages.add("Java");
        languages.add("Python");
        languages.add("Java");  // Duplicate ignored

        System.out.println(languages);  // [Java, Python] (order may vary)

        // 2. Checking size and emptiness
        System.out.println("Size: " + languages.size());  // 2
        System.out.println("Is empty? " + languages.isEmpty());  // false

        // 3. Removing elements
        languages.remove("Python");
        System.out.println(languages);  // [Java]

        // 4. Checking if an element exists
        System.out.println("Contains Java? " + languages.contains("Java"));  // true

        // 5. Iterating using Iterator
        Iterator<String> it = languages.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        // 6. Converting to array
        String[] arr = languages.toArray(new String[0]);
        System.out.println(Arrays.toString(arr));  // [Java]
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Key Points to Remember

✔ Set does not allow duplicates (unlike List).

✔ No order guarantee (except LinkedHashSet and TreeSet).

✔ No index-based operations (unlike List).

✔ Common implementations: HashSet (fastest), LinkedHashSet (ordered), TreeSet (sorted).


5. When to Use Set?

✅ When uniqueness of elements is required.

✅ When order does not matter (use LinkedHashSet for order).

✅ When sorted elements are needed (use TreeSet).


Summary Table of Key Methods

Method Action
add(E e) Adds an element if not present
remove(Object o) Removes the specified element
contains(Object o) Checks if element exists
size() Returns number of elements
iterator() Returns an iterator
toArray() Converts to array

This covers all major methods of the Set interface in Java. 🚀 Let me know if you need further clarifications!

Top comments (0)