Methods of Set

The Set interface includes all the methods of the Collection interface. It’s because Collection is a super interface of Set. 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).

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).