问题描述
使用可变对象作为 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 这样的可变对象作为键的常见做法哈希映射.
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屋!
更多推荐
[db:关键词]
发布评论