Set Interface & its implementations
πΉ What is the Set
Interface?
The Set
interface in Java is a part of the Java Collections Framework. It represents a collection of unique elements, i.e., it does not allow duplicates.
π¦ Package:
java.util.Set
π Set is an unordered collection by default (order is not guaranteed unless using specific implementations likeLinkedHashSet
orTreeSet
).
β Key Properties:
Feature | Behavior |
---|---|
Duplicates | β Not allowed |
Null values | β
Allowed (only one null value in most implementations) |
Order | β Not guaranteed (HashSet ) |
Thread-safe | β Not by default |
π§ Common Implementations of Set:
Implementation | Description |
---|---|
HashSet |
Fast, unordered, based on hash table |
LinkedHashSet |
Maintains insertion order |
TreeSet |
Sorted set (natural or custom comparator) |
π§° Common Methods in Set
:
Method | Description |
---|---|
add(E e) |
Adds element if itβs not already present |
remove(Object o) |
Removes the specified element |
contains(Object o) |
Checks if element exists |
size() |
Returns number of elements |
clear() |
Removes all elements |
isEmpty() |
Checks if the set is empty |
π Example:
π When to Use Set
?
- When uniqueness of elements is required
- When order doesn't matter (use
HashSet
) - When sorted results are needed (use
TreeSet
) - When insertion order matters (use
LinkedHashSet
)
Β
β SET Implementations:
πΉ 1. HashSet
-
Implements:
Set
interface - Underlying Data Structure: Hash Table
- Order: β No guaranteed order
- Duplicates: β Not allowed
- Nulls: β Allowed (only one)
- Performance: β Fast (O(1) for add, remove, contains)
β Use-case:
When you want unique elements and donβt care about order.
πΈ 2. LinkedHashSet
-
Implements:
Set
interface - Underlying Data Structure: Hash Table + Linked List
- Order: β Maintains insertion order
- Duplicates: β Not allowed
- Nulls: β Allowed
-
Performance: Slightly slower than
HashSet
β Use-case:
When you want unique elements in the order you added them.
πΊ 3. TreeSet
-
Implements:
NavigableSet
βSortedSet
βSet
- Underlying Data Structure: Red-Black Tree
- Order: β Sorted (natural or custom)
- Duplicates: β Not allowed
-
Nulls: β Not allowed (throws
NullPointerException
) - Performance: O(log n) for add, remove, search
β Use-case:
When you need sorted unique elements.
π¦ Summary Table:
Type | Ordered? | Sorted? | Allows Null? | Performance | Use-case |
---|---|---|---|---|---|
HashSet | β No | β No | β One | β Fastest (O(1)) | Unordered unique elements |
LinkedHashSet | β Yes (insertion) | β No | β One | β οΈ Slower than HashSet | Maintain insertion order with uniqueness |
TreeSet | β Yes | β Yes | β No | π Slower (O log n) | Need sorted unique elements |