Core Module
12 min forge
HashMap in Java
Key-value pair storage, hashing mechanism, and collision handling.
HashMap in Java
π What is it
HashMap is a part of the Java Collections Framework that stores elements in key-value pairs. It uses a hashing technique to store and retrieve elements efficiently.
β‘ When to use
Use HashMap whenever you need to associate keys with values for fast lookups, such as caching data, frequency counters, or storing configuration settings.
π§ Time complexity
- Put: $O(1)$ (average case)
- Get: $O(1)$ (average case)
- Remove: $O(1)$ (average case)
- In case of high collisions, time complexity can degrade to $O(n)$ (or $O(\log n)$ since Java 8 which uses balanced trees for long collision chains).
π» Code example
java Standardimport java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { Map<String, Integer> scores = new HashMap<>(); scores.put("Alice", 95); scores.put("Bob", 88); System.out.println("Alice's score: " + scores.get("Alice")); } }
ποΈ Internal Working
HashMap uses an internal array of nodes (buckets).
- Hashing: Computes an index using the
hashCode()method of the key. - Collision Handling: If two keys result in the same index, they are stored in a linked list (or a balanced tree if the list grows too large).
equals()&hashCode(): Essential to override both correctly in custom keys to ensure consistent behavior.
β Common mistakes
- Mutable Keys: Using mutable objects as keys (if the key changes, you might lose access to the value).
- Ignoring Load Factor: Not adjusting the initial capacity and load factor for very large maps.
- Null Values: Forgetting that
HashMapallows onenullkey and multiplenullvalues.