Java Collection Framework for Strong Senior Developers
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.
How do you implement an LRU cache using Java collections?
Use LinkedHashMap with access-order and override removeEldestEntry().
Example approach:
Construct LinkedHashMap with accessOrder=true.
Override removeEldestEntry() to return true when size exceeds the limit.
This efficiently maintains the most recently accessed entries.
Alternatives:
Use libraries like Guava Cache or Caffeine for production-grade features.
What are the performance implications of using ArrayList vs LinkedList?
ArrayList:
Backed by a dynamic array.
get(index) and set(index) are O(1).
add/remove at end is fast; insert/delete in the middle is costly (O(n)).
LinkedList:
Doubly linked list — each element points to previous and next.
get(index) is O(n), as traversal is required.
Efficient insertions/removals at beginning or middle if you already have a reference.
Guidelines:
Use ArrayList for frequent random access.
Use LinkedList for frequent insertions/removals in the middle or head.
How does fail-fast behavior work in Java collections, and how can you avoid
ConcurrentModificationException?
Fail-fast iterators throw ConcurrentModificationException if the collection is
structurally modified during iteration.
Mechanism:
Collections like ArrayList and HashMap track modificationCount.
Iterator compares expectedModCount with actual modCount on each access.
Ways to avoid exception:
Use Iterator's remove() method.
Use concurrent collections (e.g., CopyOnWriteArrayList, ConcurrentHashMap).
Collect items to remove in a temp list, and remove after iteration.
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).