哈希映射键应该是不可变的吗? [英] Should hashmap key be immutable?

查看:45
本文介绍了哈希映射键应该是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,如果我们需要将自定义对象作为键传递,我们只需要重写equals和hashcode方法,甚至该类都应该是不可变的?

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 ?

推荐答案

这取决于您的哈希函数.

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.

这篇关于哈希映射键应该是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆