In Java, the Set interface is the part of Java Collection Framework that contains no duplicates. Set interface extends the Collection interface and provides the add, remove, and check the presence of the elements.
Classes and Interface that implemented the Set Interface -
- HashSet (Implemented in LinkedHashSet)
- SortedSet ( Implemented in TreeSet)
- Does not maintain any order of the elements.
- Allows one null elements.
- Provides constant-time performance for basic operations like - add(), remove(), and contains() function.
constant-time: constants-time takes the same amount of time to complete the operation of add(), remove(), contains() functions, regardless size of the inputs. It's denoted as O(1) in big-O notation.
Use case: When we need to store unique elements and don't care about the order, in this case we can use it.
2. LinkedHashSet Class: LinkedHashSet class extends HashSet Class and it maintains insertion order with unique elements.
- Maintains the insertion order
- Slightly slower than HashSet
- Allows one null elements
Use Case: When we need a set that maintains the order of insertion with unique elements then we can use it.
3. SortedSet Interface: SortedSet extends the Set interface and ensures that the elements are in natural order or by a comparator provided at the set creation.
4. TreeSet Class: TreeSet class implements the SortedSet interface and stores elements in a Red-Black Tree (a selft-balancing binary search tree). And remain act same as SortedSet interface.
- Maintains a sorted order of elements
- Slower then HashSet and LinkedHashSet
- Does not allow null elements
Use Case: When we need to make a set as a tree structure that stores unique and sorted order elements.
0 Comments