Junior — Middle
What is the uniqueness of the LinkedHashSet data structure and how does it work?
sobes.tech AI
Answer from AI
LinkedHashSet is a data structure in Java that combines the properties of HashSet and LinkedHashMap.
Uniqueness and features:
- Stores unique elements (like HashSet).
- Preserves the insertion order of elements thanks to an internal linked list (Linked).
How it works:
- It is based on LinkedHashMap, where the set elements act as keys.
- When an element is added, it is placed in the hash table for quick lookup and simultaneously added to the linked list that maintains insertion order.
- During iteration, elements are returned in the order they were added.
Thus, LinkedHashSet provides:
- Fast access and existence check of elements (average O(1)).
- Iteration over elements in insertion order.
Example usage:
import java.util.LinkedHashSet;
public class Example {
public static void main(String[] args) {
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("apple");
set.add("banana");
set.add("cherry");
for (String fruit : set) {
System.out.println(fruit);
}
}
}
Output will be:
apple
banana
cherry
This distinguishes LinkedHashSet from a regular HashSet, which does not guarantee element order.