HashMap<K,V> stores key-value pairs with O(1) average lookup. Keys should implement consistent equals and hashCode.
Basic usage
HashMap<String, Integer> counts = new HashMap<>();
counts.put("a", 1);
counts.get("a");
counts.containsKey("a");
counts.getOrDefault("z", 0);
Iteration
for (var entry : counts.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
Important interview questions and answers
- Q: HashMap vs TreeMap?
A: HashMap unordered O(1) average; TreeMap sorted keys O(log n). - Q: Is HashMap thread-safe?
A: No—useConcurrentHashMapfor concurrent access.
Self-check
- What method retrieves a value by key?
- Why must key objects implement hashCode?
Interview prep
- Why equals and hashCode together?
Hash-based collections bucket by hash code then compare with equals—equal keys must share hash codes or lookups fail.