The Disappearing Hash Key
Active system tokens stored inside a collection structure return null even when they definitely exist in the dataset.
The setup
You are designing a real-time gateway session manager using a HashMap to link security data structures to user accounts. Users intermittently experience session drops, and lookup checks return null even though data was just inserted. Uncover the hash lookup leak.
The broken code
import java.util.*;
public class SessionTracker {
public static class AccountKey {
public String userId;
public AccountKey(String id) { this.userId = id; }
}
public static void main(String[] args) {
Map<AccountKey, String> sessionMap = new HashMap<>();
AccountKey key = new AccountKey("USER_X");
sessionMap.put(key, "ACTIVE_SESSION");
// TRAP: Attempting to look up using a logical match returns null
// because the key model doesn't override identity contracts!
System.out.println(sessionMap.get(new AccountKey("USER_X")));
}
}
Hints
- How does a HashMap determine if two objects match? It calls hashCode() and equals().
- If your custom class doesn't explicitly implement these overrides, Java falls back to Object's default behavior, which compares memory addresses.
- Implement valid equals() and hashCode() override layers based on the immutable parameters of your key class.
The fix
import java.util.*;
public class SessionTracker {
public static class AccountKey {
public String userId;
public AccountKey(String id) { this.userId = id; }
// Clean Fix: Override equals and hashCode to ensure consistent structural lookup matching
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AccountKey that = (AccountKey) o;
return Objects.equals(userId, that.userId);
}
@Override
public int hashCode() {
return Objects.hash(userId);
}
}
public static void main(String[] args) {
Map<AccountKey, String> sessionMap = new HashMap<>();
AccountKey key = new AccountKey("USER_X");
sessionMap.put(key, "ACTIVE_SESSION");
System.out.println(sessionMap.get(new AccountKey("USER_X"))); // Returns ACTIVE_SESSION
}
}
Why it breaks
The Bug: HashMap uses hashCode and equals to bucket and pinpoint keys. Without custom implementations, Java relies on memory references. Consequently, identical logical models fail lookup validation steps.