我有一个自定义类Node:

public static class Node{

    int _id;
    // adjacent node and its cost
    HashMap<Node, Integer> _adjList = new HashMap<>();

    public Node(int id){
        _id = id;
    }

    public boolean equals(Node n) {
        if (n == null)
            return false;
        return _id == n._id;
    }

    public int hashCode(){
            return _id;
    }

    public String toString(){
        return "("+_id+")";
    }

}//Node


我将其用作HashMap<Node, Integer> costs的键,对于给定的节点,到达与之关联的节点会产生成本。
在程序的后面,我用值填充了costs

{(1)=0, (2)=24, (3)=3, (4)=15}


然后,在稍后的代码中,当我像这样查询costs时:

 for (int i = 0; i <= g.nNodes; ++i){
            Node tempNode = new Node(i);
            Integer cost = currentPathCosts.get(tempNode);
            System.out.println("cost:"+cost);
        }


我懂了

null
null
null


作为输出。
怎么了?具有相同hashcode()的节点的_id应该是相同的。



更新:

我错过了Node other =(Node)n;在equals()方法中。
覆盖对我有用的hashcode()和equals()的方法:

        @Override
        public boolean equals(Object n) {
            if (n == null)
                return false;
            Node other = (Node)n;
            return _id == other._id;
        }
        @Override
        public int hashCode(){
                return _id;
        }

最佳答案

像在要覆盖方法时应始终执行的操作一样,在@Override方法上添加equals()批注,编译器将告诉您问题出在哪里。 (对hashCode进行同样的操作)。

您没有覆盖Object.equals()。您正在定义另一个不同的equals()重载方法。

10-04 15:13
查看更多