Member-only story
Why Is String
a Good Key for HashMap
in Java | Tricky Java Interview Questions — Part 16
Hello Developers,
Welcome to Part 16 of the Tricky Java Interview Questions series.
Today’s question dives into one of Java’s most-used data structures:
Why is
String
considered a good key forHashMap
in Java?
You’ve probably used Map<String, Object>
or Map<String, String>
a hundred times. But do you know why it works so well?
Let’s explore the reasons — both technical and practical.
What Makes a Good Key for a HashMap?
To work well as a key in a HashMap
, a class must:
- Be immutable
- Have a good
hashCode()
implementation - Have a correct
equals()
method - Not change while it’s being used as a key
Let’s see how String
checks all those boxes — and why that makes it ideal.
Reason 1: String
is Immutable
Immutability is the most important factor.
Map<String, String> map = new HashMap<>();
String key = "user123";
map.put(key, "John");
key = key.toUpperCase(); // changes reference, not the map key
System.out.println(map.get("user123")); // still prints "John"
If a key changes after insertion, the hash value changes too — and you won’t be able…