Java String hashCode是如何计算对象的

How is Java String hashCode calculated on objects

"Sun" 和 "TWO" 在 Java.

中给出相同的 hashCode() 值

为什么会这样输出:

HashMap<String, Integer> map = new HashMap<>();
map.put("Sun", 1);
System.out.println(map.get("TWO"));

输出:空

但是

HashMap<Integer, Integer> map = new HashMap<>();
map.put("Sun".hashCode(), 1);
System.out.println(map.get("TWO".hashCode()));

输出:1

hashmap 是否在字符串 "Sun" 上调用 hashCode() 以将其用作键?

当一个对象被插入到HashMap中时,它确实使用hashCode方法来决定存储它的位置。但是 hashCodes 并不是完全唯一的。可以有不同的值产生相同的输出但不相等,因此 HashMap 将有一些方法来处理这样的冲突。如果键具有相同的 hashCode,并且使用 equals 方法相等,则 get 只会 return 一个值。 "Sun" 不等于 "TWO",但是 "Sun" 的 hashCode 确实 等于 "TWO".

的 hashCode

来自 the documentation:

if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

因此,决定 returned 的是相等性,而不是哈希码。哈希码实际上只是一种优化,可以使查找哪些对象可能相等的过程更快。