【问题标题】:HashMap<Node, Integer> get returns null even when hashcode() is the same即使 hashcode() 相同,HashMap<Node, Integer> get 也会返回 null
【发布时间】:2017-03-18 23:44:11
【问题描述】:

我有一个自定义类节点:

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&lt;Node, Integer&gt; 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

作为输出。 怎么了?具有相同_id 的节点的hashcode() 应该相同..我错过了什么吗?


更新:

我在 equals() 方法中缺少 Node other = (Node)n;。 覆盖对我有用的 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;
        }

【问题讨论】:

    标签: java hash nullpointerexception hashmap hashtable


    【解决方案1】:

    在你的equals() 方法上添加@Override 注释,当你想要覆盖一个方法时你应该总是这样做,编译器会告诉你问题是什么。 (对 hashCode 做同样的事情,当你在它的时候)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多