Skip to content
Advertisement

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

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

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

Advertisement

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!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement