Java Set Interface

Introduction

The Set interface in Java, part of the java.util package, is a collection that does not allow duplicate elements. It models the mathematical set abstraction, providing operations to add, remove, and query elements. Common implementations include HashSet, LinkedHashSet, and TreeSet.

Table of Contents

  1. What is the Set Interface?
  2. Common Implementations
  3. Common Methods
  4. Examples of Using the Set Interface
  5. Conclusion

1. What is the Set Interface?

The Set interface extends the Collection interface and represents a collection that does not allow duplicate elements. The Set interface ensures that at most one instance of an element is present in the collection. It is widely used in situations where uniqueness is a requirement, such as in sets of keys, elements of mathematical sets, etc.

2. Common Implementations

  • HashSet: Uses a hash table for storage. It offers constant-time performance for basic operations (add, remove, contains) but does not guarantee the order of elements.
  • LinkedHashSet: Extends HashSet and maintains a linked list of the entries in the set, preserving the insertion order.
  • TreeSet: Implements the NavigableSet interface and uses a red-black tree. It orders the elements according to their natural ordering or by a specified comparator.

3. Common Methods

  • add(E e): Adds the specified element to this set if it is not already present.
  • remove(Object o): Removes the specified element from this set if it is present.
  • contains(Object o): Returns true if this set contains the specified element.
  • size(): Returns the number of elements in this set.
  • isEmpty(): Returns true if this set contains no elements.
  • clear(): Removes all of the elements from this set.
  • iterator(): Returns an iterator over the elements in this set.
  • addAll(Collection<? extends E> c): Adds all of the elements in the specified collection to this set if they’re not already present.
  • retainAll(Collection<?> c): Retains only the elements in this set that are contained in the specified collection.
  • removeAll(Collection<?> c): Removes from this set all of its elements that are contained in the specified collection.

4. Examples of Using the Set Interface

Example 1: Basic Usage with HashSet

This example demonstrates how to use a HashSet.

import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String[] args) { Set<String> set = new HashSet<>(); // Adding elements to the set set.add("One"); set.add("Two"); set.add("Three"); set.add("Four"); // Attempting to add a duplicate element set.add("One"); // Iterating over the set for (String element : set) { System.out.println(element); } // Checking if the set contains an element System.out.println("Contains 'Three': " + set.contains("Three")); // Removing an element set.remove("Two"); System.out.println("After removing 'Two': " + set); // Size of the set System.out.println("Size of the set: " + set.size()); // Clearing the set set.clear(); System.out.println("Is the set empty? " + set.isEmpty()); } } 

Output:

One Four Two Three Contains 'Three': true After removing 'Two': [One, Four, Three] Size of the set: 3 Is the set empty? true 

Example 2: Using LinkedHashSet for Ordered Elements

This example shows how to use a LinkedHashSet to maintain insertion order.

import java.util.LinkedHashSet; import java.util.Set; public class LinkedHashSetExample { public static void main(String[] args) { Set<String> set = new LinkedHashSet<>(); // Adding elements to the set set.add("One"); set.add("Two"); set.add("Three"); set.add("Four"); // Iterating over the set for (String element : set) { System.out.println(element); } } } 

Output:

One Two Three Four 

Example 3: Using TreeSet for Sorted Elements

This example demonstrates how to use a TreeSet to maintain elements in sorted order.

import java.util.Set; import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { Set<String> set = new TreeSet<>(); // Adding elements to the set set.add("Banana"); set.add("Apple"); set.add("Cherry"); set.add("Date"); // Iterating over the set for (String element : set) { System.out.println(element); } } } 

Output:

Apple Banana Cherry Date 

Example 4: Performing Set Operations

This example shows how to perform basic set operations such as union, intersection, and difference.

import java.util.HashSet; import java.util.Set; public class SetOperationsExample { public static void main(String[] args) { Set<String> set1 = new HashSet<>(); set1.add("A"); set1.add("B"); set1.add("C"); Set<String> set2 = new HashSet<>(); set2.add("B"); set2.add("C"); set2.add("D"); // Union Set<String> union = new HashSet<>(set1); union.addAll(set2); System.out.println("Union: " + union); // Intersection Set<String> intersection = new HashSet<>(set1); intersection.retainAll(set2); System.out.println("Intersection: " + intersection); // Difference Set<String> difference = new HashSet<>(set1); difference.removeAll(set2); System.out.println("Difference: " + difference); } } 

Output:

Union: [A, B, C, D] Intersection: [B, C] Difference: [A] 

Example 5: Using Set with Custom Objects

This example demonstrates how to use a Set with custom objects, requiring the implementation of equals and hashCode methods.

import java.util.HashSet; import java.util.Objects; import java.util.Set; public class CustomObjectSetExample { public static void main(String[] args) { Set<Person> set = new HashSet<>(); // Adding custom objects to the set set.add(new Person("Raj", 30)); set.add(new Person("Anita", 25)); set.add(new Person("Raj", 30)); // Duplicate based on equals() and hashCode() // Iterating over the set for (Person person : set) { System.out.println(person); } } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } 

Output:

Person{name='Raj', age=30} Person{name='Anita', age=25} 

5. Conclusion

The Set interface in Java provides a powerful way to manage collections of unique elements. By using different implementations like HashSet, LinkedHashSet, and TreeSet, developers can choose the appropriate set behavior for their use cases, whether it’s unordered, insertion-ordered, or sorted. The examples provided demonstrate common usage patterns and highlight the capabilities of the Set interface.

Leave a Comment

Scroll to Top