java.util.HashMap 得到 : does key have to be exactly the same object as what is stored in the HashMap, 或者键可以只是 "equal"

标签 java hashmap

假设我有一个 HashMap M。我想在此 HashMap 上调用“get”函数,并找到与给定对象 S 关联的值。但是我没有对对象 S 的实际引用,所以我创建了一个新对象 S_new,其内容与 S 的内容相同>。如果我调用 M.get(S_new),它会给我与键 S 关联的值吗?

最佳答案

来自 the documentation for Map#get :

public V get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, 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.)

因此,只要您传递的参数覆盖 equals,使映射键被视为等效,您就可以使用不同的实例从映射中检索值。

此外,正如@Eugene 和其他人提到的,对于 HashMap,您还必须覆盖 hashCode 方法,并确保您的实例返回与您的键相同的值。通常,最佳做法是确保您的相等实现是对称(即A.equals(B) <==> B.equals(A)), 并且相等的值应该有相同的 hashCode

关于java.util.HashMap 得到 : does key have to be exactly the same object as what is stored in the HashMap, 或者键可以只是 "equal",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45577602/

相关文章:

java - Spring Batch和Spring Integration的集成问题-“未为端点定义轮询器”异常

java - 为特定 DBMS(数据库引擎)动态设置数据源的正确方法是什么?

java - 关于HashMap,重新散列

java - JSTL 访问 HashMap 中的整数/长键

java - Swing:与标签相比的复选框间距

java - 71674705 值转换为 7.1674705E

java - Log4j 2 中的单独错误记录

java - 在 Android 中使用 Hashmap、GraphView 出现无法解析的日期错误

arrays - 哈希表 : Ransom Note - Hacker Rank in Swift Timed Out

java - 将 hashmap 的键值存储在 string[] 中