Linked HashSet and its features
A LinkedHashSet in Java is a subclass of the HashSet class and implements the Set interface. It maintains a linked list of the elements in the set, along with the hash table for fast lookup. LinkedHashSet preserves the order of insertion, meaning that it maintains the order in which elements were inserted into the set. Like HashSet, LinkedHashSet does not allow duplicate elements.
Table of Contents
Features of LinkedHashSet:
- 1. Maintains Insertion Order: LinkedHashSet maintains the order in which elements were inserted into the set. It uses a linked list to keep track of the insertion order, in addition to the hash table for fast lookup.
- 2. Fast Lookup Operations: LinkedHashSet provides fast lookup operations similar to HashSet. The contains() method allows for quick checking of whether a specific element is present in the set.
- 3. No Duplicate Elements: LinkedHashSet, like HashSet, does not allow duplicate elements. If an attempt is made to add a duplicate element, it will be ignored, as the set contains only unique elements.
- 4. Backed by Hash Table and Linked List: Internally, LinkedHashSet is implemented using a hash table data structure for fast lookup, combined with a linked list to maintain insertion order.
- 5. Constant-Time Performance for Basic Operations: LinkedHashSet offers constant-time performance for basic operations like add, remove, and contains, assuming a good hash function.
- 6. Null Elements: LinkedHashSet allows null elements. You can add a null element to a LinkedHashSet, and it will be treated as a single null value.
Example Usage of LinkedHashSet
```java
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
public static void main(String[] args) {
// Create a LinkedHashSet
Set<String> linkedHashSet = new LinkedHashSet<>();
// Add elements to the LinkedHashSet
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Cherry");
// Adding a duplicate element (ignored)
linkedHashSet.add("Banana");
// Print the LinkedHashSet
System.out.println("LinkedHashSet: " + linkedHashSet);
// Check if an element is present
System.out.println("Contains 'Banana'? " + linkedHashSet.contains("Banana"));
// Remove an element
linkedHashSet.remove("Cherry");
System.out.println("LinkedHashSet after removing 'Cherry': " + linkedHashSet);
}
}
```
In this example:
- We create a LinkedHashSet of strings and add some elements to it.
- The duplicate element “Banana” is not added to the set because LinkedHashSet does not allow duplicates.
- We print the contents of the LinkedHashSet and demonstrate the contains and remove operations.
LinkedHashSet is commonly used in scenarios where maintaining insertion order along with fast lookup operations is required. It’s suitable for scenarios where the order of elements matters, such as maintaining the order of elements in a configuration or preserving the order of user inputs.