2013-04-23 83 views
0

下面的代碼包含一組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; 
    } 
} 

回答

2

您還沒有重寫equalshashCodeAnotherObject。做到這一點,你應該得到你的期望。

+1

這是解決方案是部分錯誤的,如果重寫與CustomObject不同,它將不會返回相同的值,因此它不會在HashSet中找到。你應該提到「用CustomObject的相同邏輯覆蓋」 – cahen 2013-04-23 09:35:31

0

HashSet內部使用HashMap。您的CustomObject & AnotherObject哈希也必須等於找到它。

根據你所關心的int實現AnotherObject的hashCode。

1

這是不是一個好的做法,不要試圖讓來自不同無關的類的2個對象被認爲是平等的。

您可以通過與其他類相同的邏輯編寫hashCode()AnotherObject解決這個問題,但後來你會重複的代碼因爲這兩個類都需要,如果你希望他們將被視爲等於有它的計算方式使用HashSet

相關問題