LOGBOOK

HELP

Quiz Entry - updated: 2026.11.26

When a map implementation compares keys, why must it use equals and not ==, and how does it handle null keys?

== compares object identity, so two equal keys built separately would never match. A null-safe check is thisKey == key || (thisKey != null && thisKey.equals(key)).

In Java, a == b on objects asks "are these the same object in memory?". Keys are usually created separately from the lookup: the map holds a String read from a file, and get is called with a String the user typed. They are equal by content but different objects, so == would say no match and the map would look empty.

equals compares by content. The full check used in a simple list-based map:

if (thisKey == key || (thisKey != null && thisKey.equals(key)))
  • thisKey == key is a fast path, and it also matches when both are null.
  • thisKey != null && guards the call, so a stored null key cannot throw a NullPointerException.

Python has the same split: is tests identity, == calls __eq__. Python's dict checks the hash first, then identity as a shortcut, then ==.

From Quiz: ADS / Sets, Maps and Hash Tables | Updated: Nov 26, 2026