2017-06-02 33 views
1

我無法得到兩個不同的objectsTreeSet如果一個人的如何將兩個不同的對象放到TreeSet中?

compareTo(the other)==0. 

在某一幫助能理解這一點,我怎麼能實現它的樹集。上述程序的

public class Test 

{ 
    private static SortedSet sortedSet = new TreeSet(); 

    public static void main(String[] args) { 
     sortedSet.add(new IntegerBucket("Winner", 3)); 
     sortedSet.add(new IntegerBucket("Looser", 3)); 

     System.out.println("sortedSet has " + sortedSet.size() + " members"); 
     System.out.println(sortedSet); 
    } 

} 

class IntegerBucket implements Comparable { 
    private int value = 0; 
    private String name = null; 

    public IntegerBucket(String n, int val) { 
     name = n; 
     value = val; 
    } 

    public int getValue() { 
     return value; 
    } 

    // Comparable interface 
    public int compareTo(Object ob) { 

     return getValue() - ((IntegerBucket) ob).getValue(); 

    } 

    public String toString() { 
     return name + " " + getValue(); 
    } 
} 

輸出是:

sortedSet has 1 members 
[Winner 3] 
+0

當在Comparator傳遞你確定你正確地定義了'compareTo'方法嗎?這是你的決定 - 沒有正確和錯誤的答案 - 但你真的想要「[贏家,3] == [失敗者,3]」? –

+0

@CarlosHeuberger有更強的要求比''Comparable'帶'TreeSet' ....看到我的答案中的引用 –

+0

@CarlosHeuberger是的,它是:你的報價是「強烈建議,但不是嚴格要求[比較應該與平等一致]「;'TreeSet'說:「請注意,一套... **所保留的順序必須與...相等」。 –

回答

3

你不能,由TreeSet類的合同。

請注意,如果要正確實現Set接口,則由set(無論是否提供顯式比較器)維護的排序必須與equals保持一致。 (見相當或比較爲一致的精確定義與equals)

如果你有不同的對象(即!a.equals(b))針對a.compare(b)comparator.compare(a, b)是零,您違反本合同。

你可以做到這一點(間接地)的唯一方法是構建TreeSet(例如new TreeSet<>(someComparator)其中對象之間搶七,即引起compare(a, b)的結果是非零的。

+1

你可以請你解釋什麼時候你說tie-breaks ..:感謝advnace –

+0

「即導致比較結果(a,b)非零」 –

+0

當compareTo返回0時,TreeSet認爲元素相等。不等於對象必須返回一個非零值。並且該值(以及它對可能對象空間施加的順序)必須完整且一致(否則,您的TreeSet也將無法正常運行)。 – Thilo

相關問題