下面的代码包含一组自定义对象。我正在尝试搜索其中的对象。
我已经覆盖了 equals() 方法以将其与特定字段匹配,但我无法理解为什么它无法找到它。
“XX\t未找到\tXX”
正在打印而不是
“成立!!”
导入 java.util.HashSet;导入 java.util.Set;
public class TestEquals {
private static Set<CustomObject> setCustomObjects;
public static void main(String[] args){
setCustomObjects = new HashSet<CustomObject>();
setCustomObjects.add(new CustomObject(2, "asas"));
setCustomObjects.add(new CustomObject(3, "gdhdf"));
setCustomObjects.add(new CustomObject(4, "bnbv"));
setCustomObjects.add(new CustomObject(5, "ljhj"));
AnotherObject anObj = new AnotherObject(3, 4);
if(setCustomObjects.contains(anObj)){
System.out.println("Found!!");
}else{
System.out.println("XX\tNot Found\tXX");
}
}
}
class CustomObject {
public CustomObject(int test, String name) {
this.test = test;
this.name = name;
}
private int test;
private String name;
@Override
public boolean equals(Object obj) {
if(obj instanceof AnotherObject){
AnotherObject temp = (AnotherObject)obj;
System.out.println("test" + temp.getOtherTest());
return this.test == temp.getOtherTest();
}
return true;
}
@Override
public int hashCode() {
int hash = 22;
hash = 32 * hash + this.test;
return hash;
}
}
class AnotherObject {
public AnotherObject(int otherTest, double test2) {
this.otherTest = otherTest;
this.test2 = test2;
}
private int otherTest;
private double test2;
public int getOtherTest() {
return otherTest;
}
public void setOtherTest(int otherTest) {
this.otherTest = otherTest;
}
}