equals() 和 contains() 看似矛盾
equals() and contains() seemingly contradict
for(Context context : contexts) {
if(context.equals(c)){
System.out.println(context.equals(c)+" : "+contexts.contains(c));
}
}
contexts 是一个标准的 java TreeSet
对我来说,似乎如果这产生任何输出,它应该产生 "true : true"。奇怪的是,它总是返回 "true : false"。
查看文档;我本质上是在完全复制 .contains 函数的作用,但得到了不同的结果。
谁能解释一下?
编辑:来自 java 文档(合集):
Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).
hashcode
的实现似乎与 equals
不一致。
contains
方法将查找对象 应该 使用 hashcode
的位置。然后它将使用 equals
检查它是否 是 。
因此我建议,如果您得到 true:false
,那么您需要修复 hashcode
实现,以便
If equals
returns true
for two objects then hashcode
on the two objects return the 相同值.
使用 TreeSet
对象 应该 所在的位置使用 compareTo
进行定位,所以在那里做等效的事情。
for(Context context : contexts) {
if(context.equals(c)){
System.out.println(context.equals(c)+" : "+contexts.contains(c));
}
}
contexts 是一个标准的 java TreeSet
对我来说,似乎如果这产生任何输出,它应该产生 "true : true"。奇怪的是,它总是返回 "true : false"。
查看文档;我本质上是在完全复制 .contains 函数的作用,但得到了不同的结果。
谁能解释一下?
编辑:来自 java 文档(合集):
Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).
hashcode
的实现似乎与 equals
不一致。
contains
方法将查找对象 应该 使用 hashcode
的位置。然后它将使用 equals
检查它是否 是 。
因此我建议,如果您得到 true:false
,那么您需要修复 hashcode
实现,以便
If equals
returns true
for two objects then hashcode
on the two objects return the 相同值.
使用 TreeSet
对象 应该 所在的位置使用 compareTo
进行定位,所以在那里做等效的事情。