HashMap is an implementation of the Map interface that stores associations between unique Keys and Values. It provides near-instantaneous O(1) average time complexity for get() and put() operations.
map.put(key, value), the JVM executes a hash function: int hash = (h = key.hashCode()) ^ (h >>> 16);.index = (n - 1) & hash, where n is array capacity (default 16).Node<K,V> objects.import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, String> userRoles = new HashMap<>();
// 1. put(K, V) - Insert or overwrite
userRoles.put("aarav101", "ADMIN");
userRoles.put("sneha99", "EDITOR");
userRoles.put("vikram5", "VIEWER");
// 2. get(K) - O(1) lookup
System.out.println("Aarav's Role: " + userRoles.get("aarav101")); // ADMIN
// 3. getOrDefault() - Safe lookup without null checks
System.out.println("Unknown user: " + userRoles.getOrDefault("guest", "GUEST_ROLE"));
// 4. Iterating over Map.Entry sets:
System.out.println("
--- All Users ---");
for (Map.Entry<String, String> entry : userRoles.entrySet()) {
System.out.println("User: " + entry.getKey() + " → Role: " + entry.getValue());
}
}
}
Exam Question: "Can an object be modified after being used as a key in a HashMap?"
Answer: Dangerous Trap! If you mutate an object that is actively being used as a HashMap key, its hashCode() will change. When you later attempt to retrieve it using map.get(key), the JVM will compute the new hash code, search in the wrong bucket, and fail to find the entry (returning null)! Always use immutable classes (like String or Integer) as HashMap keys!
When you need a key-value map whose keys are sorted in strict ascending order, use TreeMap. Proceed to: Java TreeMap & SortedMap →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Sorted key-value maps.
Backed by HashMap.
SynchronizedMap wrapper.
Iterating map entry sets.