All Classes and Interface of Set Interface.

 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 - 
  1. HashSet (Implemented in LinkedHashSet)
  2. SortedSet ( Implemented in TreeSet)

1. HashSet Class: A HashSet is used to store unique elements without any specific order.
  • 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.

HashSet class code example

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.

LinkedHashSet class code example

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.
  • Set is ordered
Use Case: When we need a shorted collection of unique elements then we can use it.

SortedSet interface code example
 
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.

TreeSet class's code example




Post a Comment

0 Comments