改性按照JavaDoc of java.util.HashSet.contains()方法假如果此集合包含指定的元素不以下HashSet.contains(object)返回例如后插入
返回true。更 正式,返回true,当且仅当此set包含元素e 这样(O == NULLé== 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记住,因此它不能识别一个对象。 – Dims
[HashSet包含自定义对象的问题]的可能重复(http://stackoverflow.com/questions/5110376/hashset-contains-problem-with-custom-objects) – SpaceTrucker