In Java, the Set interface is part of the java.util package and represents a collection that does not allow duplicate elements. Here’s the syntax and a list of commonly used methods in the Set interface:
public interface Set<E> extends Collection<E> {
// Methods
}
Code language: PHP (php)
Methods:
Adding Elements:
- boolean add(E e): Adds the specified element to this set if it is not already present (optional operation).
Removing Elements:
- boolean remove(Object o): Removes the specified element from this set if it is present (optional operation).
- void clear(): Removes all of the elements from this set (optional operation).
Querying Set Information:
- int size(): Returns the number of elements in this set.
- boolean isEmpty(): Returns true if this set contains no elements.
Checking Membership:
- boolean contains(Object o): Returns true if this set contains the specified element.
Bulk Operations:
- boolean containsAll(Collection<?> c): Returns true if this set contains all of the elements of the specified collection.
- boolean removeAll(Collection<?> c): Removes from this set all of its elements that are contained in the specified collection (optional operation).
- boolean retainAll(Collection<?> c): Retains only the elements in this set that are contained in the specified collection (optional operation).
Conversion to Array:
- Object[] toArray(): Returns an array containing all of the elements in this set.
Iteration:
- Iterator<E> iterator(): Returns an iterator over the elements in this set.
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Orange");
// Adding a duplicate element (ignored in a Set)
set.add("Apple");
// Accessing elements through iteration
for (String fruit : set) {
System.out.println(fruit);
}
// Checking if set contains an element
System.out.println("Set contains Orange: " + set.contains("Orange"));
// Removing an element
set.remove("Banana");
// Size of the set
System.out.println("Size of the set: " + set.size());
// Clearing the set
set.clear();
// Checking if set is empty
System.out.println("Set is empty: " + set.isEmpty());
}
}
