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/