可变哈希图键是一种危险的做法吗? [英] Are mutable hashmap keys a dangerous practice?

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

问题描述

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

Is it bad practice to use mutable objects as Hashmap keys? What happens when you try to retrieve a value from a Hashmap using a key that has been modified enough to change its hashcode?

例如,给定

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) 会发生什么?这是安全的还是可取的?还是行为取决于语言?

What happens if we now call map.get(key1)? Is this safe or advisable? Or is the behavior dependent on the language?

推荐答案

Brian Goetz 和 Josh Bloch 等许多受人尊敬的开发人员指出:

It has been noted by many well respected developers such as Brian Goetz and Josh Bloch that :

如果一个对象的 hashCode() 值可以根据它的状态而改变,那么我们使用这些对象作为基于哈希的键时必须小心集合以确保我们不允许它们的状态在何时更改它们被用作哈希键.所有基于哈希的集合都假设一个对象的哈希值在它被用作一个对象时不会改变集合中的关键.如果一个键的哈希码在它发生变化时在一个集合中,一些不可预测和令人困惑的后果可以跟随.这在实践中通常不是问题——它不是使用可变对象(如 List)作为 a 中的键的常见做法哈希映射.

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.

这篇关于可变哈希图键是一种危险的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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