为什么HashMap的Hashcode为零

Lok*_*rma -2 java performance

我正在尝试用方法一进行初始化:

Map<String, String> mapInter = Collections.EMPTY_MAP;
mapInter = new HashMap<String, String>();
mapInter.put("one", "one");
System.out.println(mapInter.hashCode());        
Run Code Online (Sandbox Code Playgroud)

方法二:

HashMap<String, String> myMap = new HashMap<String, String>(10);
myMap.put("key", "value");
System.out.println(myMap.hashCode());
Run Code Online (Sandbox Code Playgroud)

在第一种方法中,当我打印哈希码时,它打印零,但在第二种方法中,它打印哈希码。初始化后将返回hashcode。

为什么第一个案例中的 HashCode 打印为零,而第二个案例中则不是?

Ank*_*thi 5

HashCode仅当 和 相Key同时value,才为 0。

发生这种情况是因为 HashMap 中 Entry 的 hashcode 实现,如下所示:

public final int hashCode() 
{
  return (key==null   ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode());
}
Run Code Online (Sandbox Code Playgroud)

它对^键和值的哈希码执行,如果两者相同,则始终返回 0。

在您的示例中,如果您更改,myMap.put("key", "key")那么两个映射都将返回哈希码 0。

Map<String, String> mapInter = Collections.EMPTY_MAP;
mapInter = new HashMap<String, String>();
mapInter.put("one", "one");     
System.out.println(mapInter.hashCode());
Run Code Online (Sandbox Code Playgroud)

方法二:

HashMap<String, String> myMap = new HashMap<String, String>(10);
myMap.put("key", "key");
System.out.println(myMap.hashCode());
Run Code Online (Sandbox Code Playgroud)

输出:

0
0
Run Code Online (Sandbox Code Playgroud)