“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
方法来决定将其存储在哪里。但是 hashCode
并不旨在完全唯一。可能有不同的值产生相同的输出但不相等,因此 HashMap 将有一些处理此类冲突的方法。仅当键具有相同的 hashCode
且使用 equals
方法相等时,get
才会返回值。 "Sun"
不等于 "TWO"
,但 "Sun"
的 hashCode 确实 等于“两个”
。
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.)
因此,决定返回内容的是相等性,而不是哈希码。哈希码实际上只是一种优化,可以使查找哪些对象可能相等的过程更快。
关于java - Java String hashCode是如何计算对象的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58121003/