What is Set in Java?
The Set interface is a part of the Java Collections Framework and is available in the java.util package. It represents a collection that stores unique elements, meaning duplicate values are not allowed.
Key Characteristics of Set
- A Set does not allow duplicate elements. If an attempt is made to add a duplicate element, it is ignored.
- Most Set implementations allow at most one null value. However, TreeSet does not permit null elements because it stores elements in sorted order.
- Set provides efficient operations for searching, inserting, and deleting elements.
- It does not support index-based access like the List interface.
- The order of elements depends on the implementation:
- HashSet → No guaranteed order
- LinkedHashSet → Maintains insertion order
- TreeSet → Maintains sorted order
Implementations of Set Interface
1. HashSet
HashSet is an implementation of the Set interface that stores unique elements using a hash table.
Set<String> set = new HashSet<>();
Characteristics
- Does not allow duplicates
- Allows one null value
- Does not maintain insertion order
- Fastest among Set implementations
Example
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("React");
set.add("SQL");
set.add("Java");
System.out.println(set);
}
}
Output
[React, Java, SQL]
(Order may vary.)
Internal Data Structure
Hash Table
When to Use
- Duplicates are not allowed
- Order is not important
- Fast performance is required
2. LinkedHashSet
LinkedHashSet is a HashSet that maintains insertion order.
Set<String> set = new LinkedHashSet<>();
Characteristics
- No duplicates
- Maintains insertion order
- Allows one null
- Slightly slower than HashSet
Example
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<String> set =
new LinkedHashSet<>();
set.add("Java");
set.add("React");
set.add("SQL");
System.out.println(set);
}
}
Output
[Java, React, SQL]
Order remains same as insertion order.
Internal Data Structure
Hash Table + Doubly Linked List
When to Use
- Duplicates are not allowed
- Insertion order must be preserved
3. TreeSet
TreeSet stores unique elements in sorted order.
Set<Integer> set = new TreeSet<>();
Characteristics
- No duplicates
- Automatically sorts elements
- Does not allow null
- Slower than HashSet
Example
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> set =
new TreeSet<>();
set.add(50);
set.add(10);
set.add(30);
System.out.println(set);
}
}
Output
[10, 30, 50]
Automatically sorted in ascending order.
Internal Data Structure
Red-Black Tree
(A self-balancing binary search tree.)
Top comments (0)