I have a Map that uses a Set for the key type, like this:
Map<Set<Thing>, Val> map;
When I query map.containsKey(myBunchOfThings), it returns false, and I don’t understand why. I can iterate through each key in the keyset and verify there is a key that (1) has the same hashCode, and (2) is equals() to myBunchOfThings.
System.out.println(map.containsKey(myBunchOfThings)); // false.
for (Set<Thing> k : map.keySet()) {
if (k.hashCode() == myBunchOfThings.hashCode() && k.equals(myBunchOfThings) {
System.out.println("Fail at life."); // it prints this.
}
}
Do I just fundamentally misunderstand the contract for containsKey? Is there a secret to using sets (or more generally, collections) as keys to maps?
Key should not be mutated while used in the map. The
Mapjava doc says:I knew this issue, but never made the test until now. I elaborate then a bit more:
After
key2is mutated, the map does not contain it anymore. We could think that the map “indexes” the data when it’s added and we would then expect that it still contains the key2 clone (line marked with*). But funny enough, this is not the case.So, as the java doc says, keys should not be mutated otherwise the behavior is unspecified. Period.
I guess that’s what happens in your case.