Advertisement
Google Ad Slot: content-top
Java Collection Set
A Set in Java is a collection of unique elements that does not allow duplicates. It is part of the Java Collections Framework and is useful when uniqueness is required, such as storing IDs, unique names, or distinct elements.
Set Type |
Description |
Implementation |
|---|---|---|
HashSet |
Stores unique elements with no order |
HashSet<E> |
LinkedHashSet |
Maintains insertion order |
LinkedHashSet<E> |
TreeSet |
Maintains elements in sorted order |
TreeSet<E> |
Using HashSet:
Using LinkedHashSet:
Using TreeSet:
Set Methods:
Method |
Description |
|---|---|
add(E e) |
Adds an element (ignores duplicates) |
remove(E e) |
Removes an element |
contains(E e) |
Checks if an element exists |
size() |
Returns the number of elements |
isEmpty() |
Checks if the set is empty |
clear() |
Removes all elements |
iterator() |
Returns an iterator to traverse the set |