问题描述
我读过最好在HashMap中拥有不可变对象作为关键字,因为它缓存了生成的哈希码。
一个不可变对象如何缓存哈希码默认?是不是具有不可变对象作为键的真正优势?
这不是真正的主要原因(并且不可变对象可能不会缓存它的哈希码)。
真正的(潜在的)问题是,如果密钥的哈希码在哈希映射中发生变化,则调用 map.containsKey(modifiedKey)
可能会返回false,但键仍然在地图中。
访问它的唯一方法是以重复。
请注意,实际结果可能因地图实现而异。
请参阅下面的设计例。输出是:
这意味着地图认为这个关键字不再存在,但它实际上仍然存在。
public class Test2 {
public static void main(String [] args){
Map< Mutable,String> map = new HashMap<> ();
Mutable m = new Mutable();
map.put(m,abc);
m.i = 1;
System.out.println(map.containsKey(m));
System.out.println(map.size());
System.out.println(map);
}
public static class Mutable {
int i = 0;
@Override
public int hashCode(){
return i;
}
public String toString(){
return String.valueOf(i);
}
}
}
I have read that it is better to have immutable objects as key in a HashMap because it cache the hashcode generated.
How come an immutable objects cache the hash code with default? Is it the real advantage of having immutable objects as keys?
That is not really the main reason (and an immutable object might not cache its hashcode).
The real (potential) problem is that if the hashcode of a key changes while it is in a hashmap, a call to map.containsKey(modifiedKey)
might return false, although the key still is in the map.
The only way to access it then to iterate.
Note that the actual result might vary depending on the map implementation.
See below a contrived example. The output is:
meaning that the map thinks the key is not there any more, but it actually still is.
public class Test2 {
public static void main(String[] args) {
Map<Mutable, String> map = new HashMap<> ();
Mutable m = new Mutable();
map.put(m, "abc");
m.i = 1;
System.out.println(map.containsKey(m));
System.out.println(map.size());
System.out.println(map);
}
public static class Mutable {
int i = 0;
@Override
public int hashCode() {
return i;
}
public String toString() {
return String.valueOf(i);
}
}
}
这篇关于不可变对象作为哈希集合中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!