The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
The Set interface in Java is a part of the Java Collections Framework and is part of the java.util package. It extends the Collection interface and represents a collection of unique elements. Unlike a List, a Set does not allow duplicate elements.
Key characteristics of the Set interface include:
- Uniqueness: A Set cannot contain duplicate elements. If you attempt to add an element that is already present, the set will not be modified, and the add operation will return false.
- No specific order: Unlike some other collection types, such as Lists, Sets do not guarantee any specific order of elements.
- Methods: The Set interface includes methods like
add()
,remove()
,contains()
,size()
, and others common to collections.
Here’s a simple example of using a Set in Java:
import java.util.HashSet;
import java.util.Set;
public class SetExample {public static void main(String[] args) {
// Creating a Set using HashSet
Set<String> stringSet = new HashSet<>();
// Adding elements to the Set
stringSet.add(“Apple”);
stringSet.add(“Banana”);
stringSet.add(“Orange”);
stringSet.add(“Apple”); // Duplicate element, won’t be added
// Displaying elements of the Set
System.out.println(“Set elements: “ + stringSet);
}
}
In this example, “Apple” is added only once, even though it’s attempted to be added twice, because Sets do not allow duplicates. The output will show only unique elements.