Intermediate
The Map Interface and HashMap Internals
📂 Phase 4: Collections & Error Handling (Days 17–21) · JavaA Map is like a dictionary — every key maps to exactly one value. Keys must be unique, but values can repeat freely.
Basic Map Usage
Map marks = new HashMap<>();
marks.put("Vishwas", 95);
marks.put("Rahul", 88);
marks.put("Vishwas", 99); // overwrites the previous value for this key
System.out.println(marks.get("Vishwas")); // 99
System.out.println(marks.containsKey("Rahul")); // true
How HashMap Works Internally
- Each key's
hashCode()determines which "bucket" (array index) it's stored in - Multiple keys can land in the same bucket — this is called a collision
- Since Java 8, buckets with many collisions switch from a linked list to a balanced tree for better worst-case lookup performance
HashMap vs TreeMap vs LinkedHashMap
| Implementation | Ordering | Performance |
|---|---|---|
| HashMap | No guaranteed order | O(1) average |
| LinkedHashMap | Insertion order preserved | O(1) average |
| TreeMap | Sorted by key | O(log n) |
Iterating a Map
Map scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
for (Map.Entry entry : scores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
equals() and hashCode() Contract
If you override equals() on a custom key class, you must also override hashCode() — otherwise two "equal" objects might land in different buckets and break lookups entirely.
Interview tip: A classic question is "What happens if hashCode() is the same for two different keys?" — Answer: they land in the same bucket, and equals() is then used to tell them apart. This is a normal collision, not an error.