What is the difference between HashMap, LinkedHashMap and TreeMap?
HashMap has no guaranteed order and gives O(1) operations. LinkedHashMap keeps insertion order, also in O(1). TreeMap keeps keys sorted and costs O(log n). Pick by the order you need.
Explain it simply
Three ways to keep contacts: a heap of visiting cards on a table (HashMap, quick to find but no order), a diary where you write contacts as they arrive (LinkedHashMap, remembers arrival order), and an alphabetical address book (TreeMap, always sorted but slower to update).
Example
import java.util.*;
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
for (String k : new String[]{"pune", "agra", "kochi"}) {
hash.put(k, k.length()); linked.put(k, k.length()); tree.put(k, k.length());
}
System.out.println(linked.keySet()); // prints: [pune, agra, kochi]
System.out.println(tree.keySet()); // prints: [agra, kochi, pune]
// hash.keySet() order is not guaranteedWhat to say in the interview
"HashMap uses a hash table, allows one null key, and does not promise any order. LinkedHashMap adds a doubly linked list through the entries to preserve insertion order, or access order, which is handy for an LRU cache. TreeMap uses a red-black tree for sorted keys and navigation methods, with O(log n) cost and no null keys. I default to HashMap and switch only when I need order."
Common mistakes
- Relying on HashMap's current iteration order. It can change when the map resizes.