java.util.HashSet不遵守其规范吗?

问题描述 投票:2回答:1

作为一个相对的Java菜鸟,我很困惑,找出以下内容:

point.Java:

public class Point {
...
    public boolean equals(Point other) {
        return x == other.x && y == other.y;
    }
...
}

edge.Java:

public class Edge {
    public final Point a, b;
    ...
    public boolean equals(Edge other) {
        return a.equals(other.a) && b.equals(other.b);
    }
...
}

main snippet:private Set blockedEdges;

public Program(...) {
    ...
    blockedEdges = new HashSet<Edge>();

    for (int i = 0; ...) {
        for (int j = 0; ...) {

            Point p = new Point(i, j);              
            for (Point q : p.neighbours()) {

                Edge e = new Edge(p, q);
                Edge f = new Edge(p, q);

                blockedEdges.add(e);


                // output for each line is: 
                // contains e? true; e equals f? true; contains f? false

                System.out.println("blocked edge from "+p+"to " + q+
                      "; contains e? " + blockedEdges.contains(e)+
                      " e equals f? "+ f.equals(e) + 
                      "; contains f? " + blockedEdges.contains(f));
            }
        }
    }
}

为什么这令人惊讶?因为我在编码之前检查了文档以依赖于相等而且它是says

如果此set包含指定的元素,则返回true。更正式地,当且仅当此集合包含元素e时才返回true(o == null?e == null:o.equals(e))

这句话非常清楚,它表明只需要平等。 f.equals(e)返回true,如输出中所示。很明显,集合确实包含元素e,使得o.equals(e),但包含(o)返回false。

虽然哈希集也取决于哈希值是否相同,这当然是可以理解的,但是在HashSet本身的文档中既没有提到这个事实,也没有在Set的文档中提到任何这样的可能性。

因此,HashSet不符合其规范。这看起来像是一个非常严重的错误。我在这里走错了路吗?或者接受这样的行为怎么样?

java hashset
1个回答
10
投票

你没有压倒equals(你正在超载它)。 equals需要接受Object作为参数。

做点什么

@Override
public boolean equals(Object o) {
    if (!(o instanceof Point))
        return false;
    Point other = (Point) o;
    return x == other.x && y == other.y;
}

(和Edge一样)

当你重写hashCode时,总是重写equals也很重要。例如,参见Why do I need to override the equals and hashCode methods in Java?

请注意,如果您使用过@Override,则编译会捕获此错误。这就是为什么在可能的情况下始终使用它的好习惯。

© www.soinside.com 2019 - 2024. All rights reserved.