0% completed
The Set interface is a fundamental part of the Java Collections Framework. It represents a collection that does not allow duplicate elements. Unlike lists, which maintain the order of insertion and allow duplicates, a set is all about uniqueness. This is especially useful when you need to ensure that no two elements in a collection are the same.
The Set interface extends the Collection interface, which means it inherits all the basic operations such as add()
, remove()
, size()
, and iterator()
. Additionally, it enforces the rule that no duplicates are allowed.
The following table summarizes the primary methods provided by the Set interface:
Method | Description |
---|---|
add(E e) | Adds the specified element to the set if it is not already present. |
remove(Object o) | Removes the specified element from the set if it is present. |
contains(Object o) | Returns true if the set contains the specified element. |
size() | Returns the number of elements in the set. |
clear() | Removes all elements from the set. |
iterator() | Returns an iterator over the elements in the set. |
HashSet:
LinkedHashSet:
TreeSet:
.....
.....
.....