hash - 可变 HashMap 键是一种危险的做法吗?

标签 hash key hashmap hashcode mutable

使用可变对象作为 Hashmap 键是一种不好的做法吗?当您尝试使用已修改足以更改其哈希码的键从 HashMap 中检索值时,会发生什么?

例如,给定

class Key
{
    int a; //mutable field
    int b; //mutable field

    public int hashcode()
        return foo(a, b);
    // setters setA and setB omitted for brevity
}

带有代码

HashMap<Key, Value> map = new HashMap<Key, Value>();

Key key1 = new Key(0, 0);
map.put(key1, value1); // value1 is an instance of Value

key1.setA(5);
key1.setB(10);

如果我们现在调用 map.get(key1) 会发生什么?这安全还是可取?或者行为取决于语言?

最佳答案

许多备受尊敬的开发人员(例如 Brian Goetz 和 Josh Bloch)已经指出:

If an object’s hashCode() value can change based on its state, then we must be careful when using such objects as keys in hash-based collections to ensure that we don’t allow their state to change when they are being used as hash keys. All hash-based collections assume that an object’s hash value does not change while it is in use as a key in the collection. If a key’s hash code were to change while it was in a collection, some unpredictable and confusing consequences could follow. This is usually not a problem in practice — it is not common practice to use a mutable object like a List as a key in a HashMap.

关于hash - 可变 HashMap 键是一种危险的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48231946/

相关文章:

c++ - 如何创建具有 64 位输出的良好 hash_combine(受 boost::hash_combine 启发)

ruby - 解析哈希以打印为格式良好的字符串

json - jq:删除具有空字符串值的键

python - 使用 Paramiko 更改主机 key 时自动更新 known_hosts 文件

c# - MD5 散列的奇怪行为

ruby - 如果值存在则显示散列的内容

php - 如何获取 php 键作为 php 数组中的值

java - 如何使用 HashMap 解读单词列表?

java - 从 HashMap 获取最大 Set 大小

python - 将 Ruby 哈希字符串转换为 Python 字典