【发布时间】: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<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
作为输出。
怎么了?具有相同_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