【发布时间】:2016-01-02 23:07:45
【问题描述】:
根据JavaDoc of java.util.HashSet.contains(),该方法执行以下操作
如果此集合包含指定元素,则返回 true。更多的 形式上,当且仅当此集合包含元素 e 时才返回 true 这样 (o==null ? e==null : o.equals(e)).
但这似乎不适用于以下代码:
public static void main(String[] args) {
HashSet<DemoClass> set = new HashSet<DemoClass>();
DemoClass toInsert = new DemoClass();
toInsert.v1 = "test1";
toInsert.v2 = "test2";
set.add(toInsert);
toInsert.v1 = null;
DemoClass toCheck = new DemoClass();
toCheck.v1 = null;
toCheck.v2 = "test2";
System.out.println(set.contains(toCheck));
System.out.println(toCheck.equals(toInsert));
}
private static class DemoClass {
String v1;
String v2;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((v1 == null) ? 0 : v1.hashCode());
result = prime * result + ((v2 == null) ? 0 : v2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DemoClass other = (DemoClass) obj;
if (v1 == null) {
if (other.v1 != null)
return false;
} else if (!v1.equals(other.v1))
return false;
if (v2 == null) {
if (other.v2 != null)
return false;
} else if (!v2.equals(other.v2))
return false;
return true;
}
}
打印出来:
假
是的
所以虽然equals 方法返回true,HashSet.contains() 返回false。
我猜这是因为我在将 toInsert 实例添加到集合之后对其进行了修改。
但是,这绝不是记录在案的(或者至少我找不到这样的文件)。此外,应该使用 equals 方法上面引用的文档,但似乎并非如此。
【问题讨论】:
-
你改变了哈希值,它被HashSet记住了,因此它不能识别一个对象。
标签: java collections hashset