LinkedHashSet-interview
Q1. What is LinkedHashSet in Java?
LinkedHashSet is a collection class that implements Set interface and uses a hash table + doubly-linked list. It maintains insertion order and does not allow duplicate elements.
Q2. How is LinkedHashSet different from HashSet?
Both prevent duplicates, but:
- HashSet does not maintain insertion order.
- LinkedHashSet maintains insertion order using a doubly-linked list.
Q3. What is the time complexity of LinkedHashSet operations?
Basic operations like add(), remove(), and contains() run in O(1) average time, just like HashSet.
Q4. Can LinkedHashSet store null values?
Yes, LinkedHashSet allows one null element (just like HashSet).
Q5. Give a real-world example where LinkedHashSet is better than HashSet.
When you need a unique collection with predictable iteration order, e.g., storing a list of unique usernames in the order they registered.