How do you use Set with a simple code example?

The Set interface in Java is a collection that cannot contain duplicate elements. It models the mathematical set abstraction and is part of the Java Collections Framework. The main implementations of the Set interface are HashSet, LinkedHashSet, and TreeSet.

Below is a simple example demonstrating how to use a HashSet in Java.

// Importing the required classes import java.util.HashSet; public class SetExample { public static void main(String[] args) { // Creating a HashSet HashSet set = new HashSet<>(); // Adding elements to the HashSet set.add("Apple"); set.add("Banana"); set.add("Orange"); // Attempting to add a duplicate element set.add("Apple"); // This will not be added // Displaying the elements of the HashSet System.out.println("HashSet contains: " + set); } }

Java Set HashSet Collections Framework Programming