繁体   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