![]() |
VOOZH | about |
In Java, the Set interface is a part of the Java Collection Framework, located in the java.util package. It represents a collection of unique elements, meaning it does not allow duplicate values.
The declaration of Set interface is listed below:
public interface Set<E> extends Collection <E>
Explanation: In the above example, HashSet will appear as an empty set, as no elements were added. The order of elements in HashSet is not guaranteed, so the elements will be displayed in a random order if any are added.
The image below demonstrates the hierarchy of Java Set interface.
Since Set is an interface, objects cannot be created of the typeset. We always need a class that implements this interface in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. This type-safe set can be defined as:
// Obj is the type of the object to be stored in Set
Set<Obj> set = new HashSet<Obj> ();
Set interface provides commonly used operations to manage unique elements in a collection. Now let us discuss these operations individually as follows:
To add elements to a Set in Java, use the add() method.
[A, B, C]
After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains().
Set is [A, B, C] Contains D false
The values can be removed from the Set using the remove() method.
Initial HashSet [A, B, C, D, E] After removing element [A, C, D, E]
There are various ways to iterate through the Set. The most famous one is to use the enhanced for loop.
A, B, C, D, E,
Let us discuss methods present in the Set interface provided below in a tabular format below as follows:
| Method | Description |
|---|---|
| add(element) | Adds element if not already present. Returns true if added. |
| addAll(collection) | Adds all elements from the given collection. |
| clear() | Removes all elements from the set. |
| contains(element) | Checks if the set contains the specified element. |
| containsAll(collection) | Checks if the set contains all elements from the given collection. |
| hashCode() | Returns the hash code of the set. |
| isEmpty() | This method is used to check whether the set is empty or not. |
| iterator() | This method is used to return the iterator of the set. |
| remove(element) | Removes the specified element from the set. |
| removeAll(collection) | Removes all elements in the given collection from the set. |
| retainAll(collection) | Retains only elements present in the given collection. |
| size() | Returns the number of elements in the set. |
| toArray() | This method is used to form an array of the same elements as that of the Set. |