Course contentsShow
← Java
Lesson 556 of 2,87013. The Object Class and Common MethodsFree lesson

The Lookup Failure: Finding Keys That Exist

Discover how HashMap.get returns null for keys that exist when hashCode is inconsistent.

The Lookup Failure: Finding Keys That Exist

What you'll learn: You'll discover why HashMap.get() can return null even when a key does exist in the map—if hashCode() is implemented inconsistently.

The Invisible Key Problem

Imagine a library where books are shelved by call number, but the call number printed on the book's spine doesn't match the card catalog. You'd never find the book even though it's physically there. That's exactly what happens when hashCode() returns different values for the same object at different times.

How the Failure Occurs

When you call map.put(key, value), HashMap uses key.hashCode() to determine which internal "bucket" to store the entry in. Later, when you call map.get(key), HashMap uses key.hashCode() again to find the correct bucket.

The problem: If hashCode() returns a different value the second time—maybe because it depends on a mutable field that changed—HashMap looks in the wrong bucket. The key-value pair exists in bucket A, but HashMap is searching in bucket B. Result? null, as if the key were never added.

The Frustrating Scenario

// Suppose Person's hashCode uses mutable age field
Person bob = new Person("Bob", 30);
map.put(bob, "Engineer");

bob.setAge(31);  // Oops! hashCode will now return different value

String job = map.get(bob);  // Returns null!
// Bob is still in the map, but HashMap can't find him

The key exists, the map isn't empty, but the lookup fails silently.

Key Takeaway: An inconsistent hashCode() implementation causes HashMap to lose track of entries that still exist internally. Always use immutable fields in hashCode(), and never modify objects used as keys after insertion.