簡體   English   中英

Java TreeSet無法按預期工作

[英]Java TreeSet Not Working as Expected

我建立了自己的類,該類實現了可比較的(可能不相關),並且當我嘗試使用HashSet來存儲項目時,HashSet有時聲稱該項目在HashSet中,即使它不在。 我認為這與參考檢查有關,但我確認並非如此。 怎么了?

頂點類equalsgetHashcode

public class Vertex implements Comparable<Vertex>{

    // some code ...

    @Override
    public boolean equals(Object obj) {
        Vertex other = (Vertex) obj;
        return this.getPosition().equals(other.getPosition());
    }


    @Override
    public int hashCode() {
        int hashCode1 = Integer.parseInt(this.getPosition().getX() + "" + this.getPosition().getY());
        return hashCode1;
    }
}

職位類別:

public class Position {
    private int x;
    private int y;


    public Position(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public boolean equals(Object obj) {
        Position other = (Position) obj;
        return this.x == other.x && this.y == other.y;
    }

    @Override
    public String toString() {
        //return String.format("x = %d, y = %d", x, y);
        return String.format("(%d, %d)", x, y);
    }
}

編輯:這是實現

public static void test(Vertex[][] grid) {
    TreeSet<Vertex> someSet = new TreeSet<Vertex>(){{
       add(new Vertex(new Position(3, 4), false));
        add(new Vertex(new Position(0, 5), false));
    }};
    Vertex v = new Vertex(new Position(2, 5), false);
    if (someSet.contains(v)) {
        System.out.println("error");
    } else {
        System.out.println("ok");
    }
}

上面打印error

通過您的hashcode計算,點(1,12)(11,2)將被視為相同。

有關哈希碼的建議,請參見哈希碼最佳實現方法

我解決了這個問題。 正如@NicolasFilotto指出的那樣,我沒有提到compareTo函數。 根據過去的文章 ,TreeSet 使用hashCode而是使用compareTo (我假設是用於二進制搜索)。 這就是我的測試用例失敗的原因。

暫無
暫無

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

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