Java Set Interface
In Java, the Set
interface is a part of the java.util
package and provides an unordered collection of unique elements. In other words, it contains no duplicate elements and it provides methods to add, remove, and check for the presence of an element.
The Set
interface extends the Collection
interface, and unlike List
, it does not provide a way to access elements by their index.
The most commonly used classes that implement the Set
interface are:
HashSet
: ASet
implementation that uses a hash table to store elements. It provides constant-time performance for basic operations like add, remove, and contains.TreeSet
: ASet
implementation that uses a tree to store elements. It orders the elements based on their natural ordering or using a custom comparator.LinkedHashSet
: ASet
implementation that extendsHashSet
and maintains a linked list of the elements in the order they were inserted.
Here are some of the methods provided by the Set
interface:
add(element)
: Adds the specified element to the set if it is not already present.remove(element)
: Removes the specified element from the set if it is present.contains(element)
: Returnstrue
if the set contains the specified element.size()
: Returns the number of elements in the set.isEmpty()
: Returnstrue
if the set is empty.clear()
: Removes all elements from the set.
Here's an example of using a HashSet
:
import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String[] args) { // Creating a HashSet Set<String> set = new HashSet<>(); // Adding elements to the HashSet set.add("apple"); set.add("banana"); set.add("orange"); set.add("apple"); // adding a duplicate element // Printing the elements of the HashSet System.out.println(set); // Removing an element from the HashSet set.remove("banana"); // Checking if an element is present in the HashSet System.out.println(set.contains("orange")); // Printing the size of the HashSet System.out.println(set.size()); // Clearing the HashSet set.clear(); // Checking if the HashSet is empty System.out.println(set.isEmpty()); } }
Output:
[orange, banana, apple] true 3 true
In this example, a HashSet
is created and elements are added to it. Since HashSet
does not allow duplicate elements, the second call to add
with the "apple" element is ignored. The remove
method is used to remove the "banana" element from the set, and the contains
method is used to check if the "orange" element is present in the set. The size
method is used to print the number of elements in the set, and the clear
method is used to remove all elements from the set. Finally, the isEmpty
method is used to check if the set is empty.