gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:42:20 24 4
gpt4 key购买 nike

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/

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