Java Set Interface

The set interface is present in java.util package and extends the Collection interface. Set is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Collection interface and adds a feature that restricts the insertion of the duplicate elements. There are two interfaces that extend the set implementation namely SortedSet and NavigableSet.

There are 4 different classes in Set interface.

  1. ▪ HashSet
  2. ▪ LinkedHashSet
  3. ▪ EnumSet
  4. ▪ TreeSet

List of interfaces that extends Set
  1. ▪ SortedSet
  2. ▪ NavigableSet
Set Interface methods

Some of the commonly used methods of the Collection interface that's also available in the Set interface are:

  1. add() - adds the specified element to the set
  2. addAll() - adds all the elements of the specified collection to the set
  3. iterator() - returns an iterator that can be used to access elements of the set sequentially
  4. remove() - removes the specified element from the set
  5. removeAll() - removes all the elements from the set that is present in another specified set
  6. retainAll() - retains all the elements in the set that are also present in another specified set
  7. clear() - removes all the elements from the set
  8. size() - returns the length (number of elements) of the set
  9. toArray() - returns an array containing all the elements of the set
  10. contains() - returns true if the set contains the specified element
  11. containsAll() - returns true if the set contains all the elements of the specified collection
  12. hashCode() - returns a hash code value (address of the element in the set)

Set Operations

The Java Set interface allows us to perform basic mathematical set operations like union, intersection, and subset.

  1. Union - to get the union of two sets x and y, we can use x.addAll(y)
  2. Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)
  3. Subset - to check if x is a subset of y, we can use y.containsAll(x)