Core Java
core29HashMapDemo
- Path
- pkg1core/core29HashMapDemo.java
- Package
- pkg1core
- Study order
- 29
- Run
- Single-file source launch
- Command
- java pkg1core/core29HashMapDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core29HashMapDemo.java5 * ---------------------6 * java.util.HashMap as a teaching focus: put/get/update, and why map keys7 * need stable equals() and hashCode().8 *9 * EXPLANATION:10 * - Keys are unique; put with an existing key replaces the value.11 * - Lookup uses hashCode (bucket) then equals (match within the bucket).12 * - Mutating a key after put can make the entry unfindable.13 *14 * See also: core19CollectionsDemo (Map among other collections),15 * pkg3datastructures/datastructures6HashTableImpl (under the hood).16 */17import java.util.HashMap;18import java.util.Map;19import java.util.Objects;20 21public class core29HashMapDemo {22 23 /** Mutable on purpose — shows why map keys must stay stable. */24 static class MutableId {25 int id;26 MutableId(int id) { this.id = id; }27 28 @Override29 public boolean equals(Object o) {30 return o instanceof MutableId other && id == other.id;31 }32 33 @Override34 public int hashCode() {35 return Objects.hash(id);36 }37 38 @Override39 public String toString() {40 return "id=" + id;41 }42 }43 44 public static void main(String[] args) {45 Map<String, Integer> ages = new HashMap<>();46 ages.put("Ana", 20);47 ages.put("Bob", 19);48 ages.put("Ana", 21); // update existing key49 System.out.println("ages=" + ages + " get(Ana)=" + ages.get("Ana"));50 System.out.println("getOrDefault(Zed)=" + ages.getOrDefault("Zed", 0));51 ages.merge("Bob", 1, Integer::sum);52 System.out.println("after merge Bob=" + ages.get("Bob"));53 54 // One null key is allowed (special case — prefer clear keys in new code)55 Map<String, String> labels = new HashMap<>();56 labels.put(null, "missing-key");57 System.out.println("null key value=" + labels.get(null));58 59 // Key contract: equal keys share a slot; mutating hash fields breaks lookup60 Map<MutableId, String> byId = new HashMap<>();61 MutableId key = new MutableId(7);62 byId.put(key, "task-7");63 System.out.println("before mutate: get=" + byId.get(key) + " containsKey=" + byId.containsKey(key));64 65 key.id = 99; // changes equals/hashCode66 System.out.println("after mutate: get=" + byId.get(key) + " containsKey=" + byId.containsKey(key));67 System.out.println("map still holds one entry: " + byId); // entry is effectively lost to lookup68 69 MutableId sameAsOriginal = new MutableId(7);70 System.out.println("lookup with id=7 again: " + byId.get(sameAsOriginal)); // usually null now71 }72}