The Set interface is a fundamental part of the Java Collections Framework. It represents a collection that contains no duplicate elements, making it ideal for storing unique values.
Java provides several implementations of the Set interface:
Here's a simple example demonstrating how to create and use a Set:
import java.util.HashSet;
import java.util.Set;
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // This won't be added as it's a duplicate
System.out.println(fruits); // Output: [Apple, Orange, Banana]
The Set interface provides several useful methods:
add(E e)
: Adds an element to the setremove(Object o)
: Removes an element from the setcontains(Object o)
: Checks if the set contains a specific elementsize()
: Returns the number of elements in the setclear()
: Removes all elements from the setSets in Java support mathematical set operations:
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
// Union
set1.addAll(set2);
// Intersection
set1.retainAll(set2);
// Difference
set1.removeAll(set2);
Consider these factors when selecting a Set implementation:
For most use cases, HashSet provides excellent performance. If you need a sorted set, consider using TreeSet.
equals()
and hashCode()
methods for custom objects stored in HashSetTo deepen your understanding of Java collections, explore these related topics:
By mastering the Set interface and its implementations, you'll be well-equipped to handle unique collections efficiently in your Java programs.