Card 05/ 08
Overriding equals Without hashCode Loses HashMap Entries
The entry went in, the size says it is there, and an equal key gets null.
If a class overrides equals but not hashCode, two equal objects usually have different hash codes. A HashMap then searches the wrong bucket, one of the internal slots it sorts entries into, for an equal key, and get returns null for an entry that is there. Override both, from the same fields.
You put an entry in, you look it up with a key you are certain is equal, and you get null. The map's size says the entry is in there:
class Order {
final String reference;
@Override public boolean equals(Object o) {
return o instanceof Order other && reference.equals(other.reference);
}
}Map<Order, String> map = new HashMap<>();
map.put(new Order("AB-1"), "paid");
System.out.println(map.size());
System.out.println(map.get(new Order("AB-1")));1
nullhashCode was not overridden, so it still gives every object its own number. The two Order objects are equals and have different hash codes, so they map to different buckets, and get searched a bucket the entry was never in.
Override the two together, from the same fields, every time. Most tools generate both from a menu, a record supplies both, and Objects.hash(...) writes the second one in a line.
@Override public int hashCode() {
return Objects.hash(reference);
}← → move through sections and cards