What is the equals and hashCode contract in Java, and what actually breaks when you break it?
The contract has one sentence in it, and it is the sentence that people break.
Here is the sentence. If one object is equal to another, then the two of them must have the same hash code. So if a.equals(b) is true, then a.hashCode() and b.hashCode() must be the same number.
Why does that matter? Because the hash code is what a HashMap or a HashSet uses to decide where to look. The map works out the hash code of the key, uses it to pick a bucket, and then compares the keys inside that bucket with the equals method. If two equal keys have different hash codes, they end up in different buckets, so the map can never find the second one.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Map<Key, String> map = new HashMap<Key, String>();
map.put(new Key("a"), "the value");
// A new object with the same content is a different key.
Key lookup = new Key("a");
System.out.println("equals says the same : " + lookup.equals(new Key("a")));
System.out.println("but the map cannot find it : " + map.get(lookup));
// A set behaves in the same way.
Set<Key> set = new HashSet<Key>();
set.add(new Key("a"));
set.add(new Key("a"));
System.out.println("the set has " + set.size() + " entries, not 2");
}
}
class Key {
private final String value;
Key(String value) {
this.value = value;
}
@Override
public int hashCode() {
// Only the identity hash, which is different for every object.
return System.identityHashCode(this);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Key)) {
return false;
}
Key that = (Key) other;
return this.value.equals(that.value);
}
}
So what breaks when you break the contract? Two things. If the equals method says two objects are the same and the hash codes are different, then one of them goes missing from a map or a set, and nothing throws an error. If the hash codes are the same for everything, then all the entries land in one bucket, and the map works but it is as slow as an ordinary list.
The next question in this topic shows how to write the two methods properly.