JavaSet
Java Set Interface
TheSet interface is part of theJava Collections Framework and is used to store a collection ofunique elements.
Unlike aList, aSet doesnot allow duplicates, and it does not preserve the order of elements (unless you're usingTreeSet orLinkedHashSet).
Common classes that implementSet:
HashSet- fast and unorderedTreeSet- sorted setLinkedHashSet- ordered by insertion
Tip: Use aSet when you need to store unique values only.
Common Set Methods
| Method | Description |
|---|---|
add() | Adds an element if it's not already in the set |
remove() | Removes the element from the set |
contains() | Checks if the set contains the element |
size() | Returns the number of elements |
clear() | Removes all elements |
Set vs. List
| List | Set |
|---|---|
| Allows duplicates | Does not allow duplicates |
| Maintains order | Does not guarantee order |
| Access by index | No index-based access |
Next, you'll explore theHashSet class in detail.

