The Set interface in Java is part of the Collection Framework. It represents a collection that does not allow duplicate elements. Sets are commonly used when uniqueness of data is important.
The Set interface is implemented by several classes such as:
// Creating a HashSet to store unique values
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple");
System.out.println(fruits);
}
}
Even though "Apple" is added twice, it appears only once in the output. This proves that Set automatically removes duplicate elements.
Try adding items below. If you add a duplicate, the Set will reject it!