Java – what happens when you look in a HashMap or HashSet when the object hashcode changes

In HashMap, the hash code of the provided key is used to put the value in the hash table In HashSet, hash codes are used to place values in the underlying hash table That is, the advantage of HashMap is that you have the flexibility to decide what you need as the key so that you can do such a good thing

Map<String,Player> players = new HashMap<String,Player>();

This can map strings such as player names to the player itself

My question is what happens when the hashcode of the key changes

What I expect is not a major problem of hashitou, because I will not expect and do not want to change the key In the previous example, if the player's name changes, he is no longer that player However, I can use other fields with key changes to find a player, not the name and future searches will work

However, in the HashSet, because the hash code of the whole object is used to place items, if someone changes the object slightly, the future lookup of the object will no longer resolve to the same location in the hashtable because it depends on the hashcode of the whole object Does this mean that once the data is in the HashSet, it should not be changed Or do you need to call again? Or automatic? What the hell is going on?

Solution

In your example, a string is immutable, so its hashcode cannot be changed But suppose that if the hash code of an object does change and a key in the hash table, it may disappear, as far as hash table lookup is concerned In this answer, I introduced a related question in detail: https://stackoverflow.com/a/13114376/139985. (the original question is about a HashSet, but a HashSet is really the cover of a HashMap, so the answer also covers this example.)

To be sure, if the key of HashMap or treemap is mutated in a way that affects their respective hashcode () / equals (object) or compare (...) or CompareTo (...) contracts, the data structure will be "broken"

Yes

It will not be automatically reopened HashMap will not notice that the hash code of the key has changed In fact, when HashMap is resized, you won't even recalculate hashcode The data structure remembers the original hash code value to avoid recalculating all hash codes when the hash table is resized

If you know that the hash code of the key will be changed, you need to delete the entry from the table and add it again before changing the key (if you try to delete / place after the mutation key, the deletion will not find the entry.)

What happened was that you violated the contract specified in HashMap JavaDocs Don't do that

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>