下面的代码包含一组自定义对象。我正在尝试搜索其中的一个对象。
我已经重写了 equals() 方法以将其与特定字段进行匹配,但我无法理解为什么它找不到它。
"XX\tNot Found\tXX"
正在打印 的
"Found!!"
导入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;
}
}
最佳答案
您尚未覆盖 AnotherObject
中的 equals
和 hashCode
。这样做,您应该会得到您所期望的结果。
关于java - 如何在一组自定义对象中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16165258/