Skip to main content
equals, hashCode, compareTo · Topic 5 of 6

Mutable keys

Definition​

If a field used by hashCode changes after the object is stored in a HashMap or HashSet, the object sits in the wrong bucket and can no longer be found. Use immutable objects (or records) as keys.

Example code​

A key that changes after it was stored

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

class Tag {
String name;
Tag(String name) { this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Tag t && t.name.equals(name); }
@Override public int hashCode() { return Objects.hash(name); }
}

record SafeTag(String name) { } // a record is immutable: safe as a key

class Demo {
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
Tag java = new Tag("java");
tags.add(java);

java.name = "kotlin"; // the key changes after storing
System.out.println(tags.contains(java)); // false: now looks in another bucket
System.out.println(tags.size()); // still stored, but unreachable

Set<SafeTag> safe = new HashSet<>();
safe.add(new SafeTag("java"));
System.out.println(safe.contains(new SafeTag("java")));
}
}

// Output:
// false
// 1
// true

Finished this page? Track your progress (saved only in your browser).