下面的代碼包含一組CustomObject。我試圖在其中搜索一個對象。如何在一組自定義對象中查找對象
我已經重寫equals()方法來匹配它與一個特定的領域,我不明白爲什麼它無法找到它。
「XX \ tNot實測值\ TXX」
是越來越印刷代替的
「找到!!」
import java.util.HashSet; import 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;
}
}
這是解決方案是部分錯誤的,如果重寫與CustomObject不同,它將不會返回相同的值,因此它不會在HashSet中找到。你應該提到「用CustomObject的相同邏輯覆蓋」 – cahen 2013-04-23 09:35:31