The Set Interface in Java
In Java, the Set
interface is a member of the java.util
package and extends the Collection
interface. It represents a collection of unique elements, that is, a collection in which no element can occur more than once.
The Set
interface is an interface and does not have any implementation class. It is used as the superinterface for several subinterfaces and concrete classes, such as HashSet
, LinkedHashSet
, and TreeSet
.
Here is an example of how to use the Set
interface:
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// Create a set
Set<String> set = new HashSet<>();
// Add elements to the set
set.add("A");
set.add("B");
set.add("C");
// Add an element that already exists in the set
set.add("A"); // the set will not contain a duplicate element
// Check if the set contains a specific element
boolean containsA = set.contains("A"); // returns true
boolean containsD = set.contains("D"); // returns false
// Get the size of the set
int size = set.size(); // returns 3
}
}
In this example, we create a set of strings using a HashSet
and add elements to the set using the add()
method. We then use the contains()
method to check if the set contains a specific element and the size()
method to get the size of the set.
The Set
interface is a useful and convenient way to store and work with collections of unique elements. It is an essential part of the Java Collections Framework and is used in a wide range of applications.