将可变对象用作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
}
Run Code Online (Sandbox Code Playgroud)
用代码
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);
Run Code Online (Sandbox Code Playgroud)
如果我们现在打电话map.get(key1)
怎么办?这是安全的还是可取的?或者行为是否依赖于语言?