我刚刚做了以下代码:
import java.util.HashSet;
import java.util.Set;
public class MyClass {
private static class MyObject {
private int field;
public int getField() {
return field;
}
public void setField(int aField) {
field = aField;
}
@Override
public boolean equals(Object other) {
boolean result = false;
if (other != null && other instanceof MyObject) {
MyObject that = (MyObject) other;
result = (this.getField() == that.getField());
}
return result;
}
@Override
public int hashCode() {
return field;
}
}
public static void main(String[] args) {
Set<MyObject> mySet = new HashSet<MyObject>();
MyObject object = new MyObject();
object.setField(3);
mySet.add(object);
object.setField(5);
System.out.println(mySet.contains(object));
MyObject firstElement = mySet.iterator().next();
System.out.println("The set object: " + firstElement + " the object itself: " + object);
}
}
它打印:
false
The set object: MyClass$MyObject@5 the object itself: MyClass$MyObject@5
基本上意味着object
不被认为在集合中,而它的实例本身显然在集合中。这意味着如果我在集合中插入一个对象,然后更改参与方法计算的字段的值hashCode
,那么该HashSet
方法将按预期工作。这不是可能的错误的太大来源吗?有人如何为此类案件辩护?