假设我有一个 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 returnsv
; otherwise it returnsnull
. (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/