为什么AbstractCollection没有实现equals()? [英] Why AbstractCollection does not implement equals()?
问题描述
你知道吗:
Map<Object,Object> m1 = new HashMap<Object, Object>();
Map<Object,Object> m2 = new HashMap<Object, Object>();
System.out.println("m1.equals(m2) = "+m1.equals(m2));
System.out.println("m1.keySet().equals(m2.keySet()) = "
+m1.keySet().equals(m2.keySet()));
System.out.println("m1.entrySet().equals(m2.entrySet()) = "
+m1.entrySet().equals(m2.entrySet()));
System.out.println("m1.values().equals(m2.values()) = "
+m1.values().equals(m2.values()));
会输出:
would output :
m1.equals(m2) = true
m1.keySet().equals(m2.keySet()) = true
m1.entrySet().equals(m2.entrySet()) = true
m1.values().equals(m2.values()) = false
这是由于 AbstractCollection
(其中 HashMap $ Values
继承自)不会覆盖 #equals()
。
This is caused by the fact that AbstractCollection
(which HashMap$Values
inherits from) does not overrides #equals()
.
你知道这是为什么吗?
Do you have an idea why this is so ?
推荐答案
根据 Collection#equals()
,没有通用的equals()方法对于集合
s,因此 AbstractCollection
不能提供一个。
Per the contract of Collection#equals()
, there is no general-purpose equals() methods for Collection
s, and thus AbstractCollection
cannot provide one.
请注意, HashMap $ Values
既不是一个Set也不是一个List,因此这是一个窘境,在某种意义上它不支持它的原因 equals()
。
Note that HashMap$Values
is neither a Set nor a List, thus the quandary and in a sense the reason it does not support equals()
.
这篇关于为什么AbstractCollection没有实现equals()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!