How could a LinkedHashMap fail to find an entry produced by an iterator?

Tags: , ,



Under what circumstances given a correct implementation of hashCode and equals() can the following code return false?

myLinkedHashMap.containsKey(myLinkedHashMap.keySet().iterator().next())

Answer

Most likely scenario I can think of would be even though hashCode is “deterministic”, it may be based on mutable fields. If you change the fields used to compute hashCode after it’s put in the Map, then you won’t be able to find it anymore.

Edit: should clarify you ‘usually’ won’t be able to find it anymore. Occasionally it will still work since two numbers can still rehash into the same bucket. This, of course, only adds to the confusion when it happens!



Source: stackoverflow