In Java, a Set is a collection interface that stores unique elements, meaning it does not allow duplicate values. It is part of the Java Collections Framework and provides methods for basic collection operations.
Key Features:
1. No Duplicates: Ensures all elements are unique.
2. Unordered: Elements are not stored in a specific order.
3. Implements Collection Interface: Inherits common collection methods like add(), remove(), and contains().
Types of Sets:
1. HashSet: Backed by a hash table, provides constant-time performance for basic operations but does not maintain any order.
2. LinkedHashSet: Maintains insertion order while offering similar performance as HashSet.
3. TreeSet: Implements NavigableSet, maintains elements in a sorted order, and is backed by a tree structure.
Example:
Set<String> set = new HashSet<>();
set.add(“A”);
set.add(“B”);
set.add(“A”); // Duplicate, won’t be added
Sets are ideal for collections where uniqueness is a priority.