gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:06:41 26 4
gpt4 key购买 nike

使用可变对象作为 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/57723337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com