This question already has answers here:
When overriding equals in Java, why does it not work to use a parameter other than Object?
                                
                                    (7个答案)
                                
                        
                                3年前关闭。
            
                    
我在玩Java中的HashMaps,偶然发现了我无法理解的东西。我似乎也找不到在此重复的问题。

我正在尝试创建一个具有VertexPair键和Integer值的地图。 VertexPair只是2个Vertex对象的容器。当我创建2个具有相同哈希码并且相等(由.equals()验证)的VertexPairs时,它们不会从我的地图中返回相同的值。

这是我的代码:

HashMap<VertexPair, Integer> edges = new HashMap<VertexPair, Integer>();

Vertex a = new Vertex("A");
Vertex b = new Vertex("B");

VertexPair p = new VertexPair(a, b);
VertexPair m = new VertexPair(a, b);
VertexPair n = new VertexPair(b, a);
VertexPair check = new VertexPair(a, new Vertex("C"));

System.out.println(p.equals(m));
System.out.println(p.equals(n));
System.out.println(m.equals(n));
//just to be sure equals is working
System.out.println(p.equals(check));

System.out.println(m.hashCode());
System.out.println(n.hashCode());
System.out.println(p.hashCode());
//just to be sure hashCode is working
System.out.println(check.hashCode());

edges.put(p, 10);

System.out.println(edges.get(p));
System.out.println(edges.get(m));
System.out.println(edges.get(n));


它的输出是:

true
true
true
false
1757285723
1757285723
1757285723
-425440240
10
null
null


这是所请求的VertexPair类:

public final class VertexPair {

    private HashSet<Vertex> set;

    public VertexPair(Vertex a, Vertex b) {
        if(a==null || b==null)
            throw new NullPointerException("Vertexes must not be null");
        set = new HashSet<Vertex>();
        set.add(a);
        set.add(b);
    }

    public HashSet<Vertex> getVertexes() {
        return set;
    }

    @Override
    public int hashCode() {
        return set.hashCode();
    }

    public boolean equals(VertexPair p) {
        if(!(p instanceof VertexPair))
            return false;
        if(p==this)
            return true;
        return set.equals(p.getVertexes());

    }


}


有人可以告诉我发生了什么吗?我一定对HashMaps的一些关键误解。提前致谢 :)

最佳答案

更换

public boolean equals(VertexPair p) {




@Override
public boolean equals(Object p) {

关于java - HashMap-不为相等的键返回正确的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35243185/

10-11 05:05