java - 为什么在将项目添加到 HashMap 之前 hashCode() 返回零?

标签 java

Map map = new HashMap();
System.out.println("hashCode:"+map.hashCode()); //hashcode==0 why?

map.put("test","test");
System.out.println("hashCode:"+map.hashCode()); //hashcode be okay here

如何在 Map map = new HashMap(); 之后获取 hashCode? (例如:new Object().hashCode())

最佳答案

来自documentation :

The hash code of a map is defined to be the sum of the hash codes of each entry in the map's entrySet() view. This ensures that m1.equals(m2) implies that m1.hashCode()==m2.hashCode() for any two maps m1 and m2, as required by the general contract of Object.hashCode().

由于您的 HashMap(派生自 AbstractMap)最初是空的,因此总和为零。

关于java - 为什么在将项目添加到 HashMap 之前 hashCode() 返回零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6618364/

相关文章:

java - 如何按照选择的顺序从 JList 获取项目?

Java Tiled map 正在横向绘制

java - 为什么我的 getY() 返回 0?

java - 如果之前在 IntelliJ 中运行过 shell 脚本,调试器不会将自身附加到远程目标

java - 使用 Mockito 在 Java 中模拟谓词

java - 如何在基于 Java 的应用程序服务器上使用 GCM 向 iOS 设备发送推送通知

java - 在 Firebase 中使用数据集/组

java - 数字总和程序错误

java - 生成SDK时发生内部错误

java - 构建热点时操作系统不支持错误