Card 05/ 08
All 8 cards
GotchaDifficulty: Advanced1 min
Why Your Key Went Into the Map and Never Came Out
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);
}