簡體   English   中英

Java:在NavigableSet中添加相同的對象被拒絕

[英]Java: Adding the same object in a NavigableSet rejected

這是我的代碼:

導入java.util。*;

public class AnotherBackedCollectionsTest{

public static void main(String... args){

    Shape square = new Shape("square");
    Shape circle = new Shape("circle");
    Shape triangle = new Shape("triangle");

    NavigableSet<Shape> shapes = new TreeSet<Shape>();
    shapes.add(square);
    shapes.add(circle);
    shapes.add(triangle);

    System.out.println("New shape added? " +shapes.add(new Shape("square")));

    for(Shape s : shapes){
        System.out.println(s.getName());
    }


    Set<Shape> shapes2 = new HashSet<Shape>();
    shapes2.add(square);
    shapes2.add(triangle);
    shapes2.add(circle);

    System.out.println("New shape added? " +shapes2.add(new Shape("square")));

    for(Shape s : shapes2){
        System.out.println(s.getName());
    }

}

}

class Shape implements Comparable<Shape>{

private String name;

public Shape(String name){
    this.name = name;
}

public String getName(){
    return this.name;
}

public int compareTo(Shape shape){
    return this.name.compareTo(shape.getName());
}

}

我得到以下輸出:

New shape added? false
circle
square
triangle
New shape added? true
triangle
square
square
circle

如您所見,我沒有在Shape對象上覆蓋equals()方法。 我發現這很奇怪,是當我嘗試在NavigableSet添加另一個名稱為“ square”的Shape對象時,它以某種方式拒絕了它。 是因為Shape implements Comparable<T>所以它使用了重寫的compareTo()方法來確定方法的相等性?

基本上,我要問的是NavigableSet如何確定我要添加一個重復的對象,實際上,我沒有覆蓋equals()方法。

TreeSet不使用equals()比較元素。 它使用Comparable接口。

文檔中

TreeSet實例使用其compareTo (或compare )方法執行所有元素比較,因此從集合的角度來看,此方法認為相等的兩個元素相等。

正如文檔還指出的那樣,如果您希望您的集合遵守常規的Set合約,則必須以與compareTo()一致的方式定義equals() compareTo()

即使集合的順序與equals不一致,它的行為也是明確定義的; 它只是不遵守Set接口的一般約定。

另一方面, HashSet確實使用equals()hashCode() ,並且不關注compareTo()

這解釋了行為上的差異。

簡而言之,要使您的元素盡可能廣泛地兼容,請確保重寫equals()hashCode() ,並實現Comparable接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM