Java_Collections_Interview_Problems
Java_Collections_Interview_Problems
How would you decide between using HashMap, LinkedHashMap, and TreeMap
in a performance-sensitive application?
HashMap:
Provides constant-time performance for get/put on average.
Unordered — does not maintain insertion or sorted order.
LinkedHashMap:
Maintains insertion order (or access order if configured).
Slightly slower than HashMap due to linked list overhead.
Useful for LRU cache implementations.
TreeMap:
Implements SortedMap using Red-Black Tree.
Maintains keys in natural or custom comparator order.
get/put operations are O(log n) — slower than HashMap but sorted.
Decision factors:
Need ordering? Use LinkedHashMap or TreeMap.
Need sorted keys? Use TreeMap.
Need best performance with no ordering? Use HashMap.
What is the difference between HashSet and TreeSet, and when would you use
each?
HashSet:
Backed by HashMap.
Provides constant-time add, remove, contains (on average).
Does not maintain any order.
TreeSet:
Backed by TreeMap (Red-Black Tree).
Maintains sorted order according to natural/comparator ordering.
All operations are O(log n).
Use HashSet when:
You only need fast set operations and don’t care about order.
Use TreeSet when:
You need elements in a sorted order.
You need range queries or subset views (e.g., headSet, tailSet).