Should hashmap key be immutable?

荒凉一梦 提交于 2019-12-20 06:18:16

问题


I have a question, if we need to pass custom object as a key, we just need to override equals and hashcode methods or even the class should be immutable?

because string is immutable so we prefer it as a key in hashmap, so with that logic i have raised this question ?


回答1:


It depends on your hashing function.

All data that is being hashed should be immutable. Otherwise you will lose access to your value once you alter one of those fields, until you pass another object which hashes the same way. The odds of finding your value again using any other key object is quite low.



来源:https://stackoverflow.com/questions/41299460/should-hashmap-key-be-immutable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!