我是哈希话题的新手。为了进行试验,我有一个Node类,它使用2个整数作为2D平面的坐标。但是,将节点添加到HashMap后,我无法使用键来检索它们(返回null)。下面是Node类,它同时实现Object类的hashCode()和equals()。这里有什么问题?函数本身吗?还是对哈希的误解?
public static class Node {
public int x, y;
public boolean visited;
public ArrayList<Node> neighbours;
public Node(int x, int y) {
this.x = x;
this.y = y;
neighbours=new ArrayList<>();
}
public void addneighbours(Node neighbourNode)
{
neighbours.add(neighbourNode);
}
public void removeNeighbour(Node neighbourNode) {
for (int i = 0; i < neighbours.size(); i++) {
if (neighbours.get(i).equals(neighbourNode)) {
neighbours.remove(i);
}
}
}
public ArrayList<Node> getNeighbours() {
return neighbours;
}
public void setNeighbours(ArrayList<Node> neighbours) {
this.neighbours = neighbours;
}
public int hashCode() {
return ((x + y)*(x + y + 1)/2) + y;
}
public boolean equals(Node n) {
if (n.x == x && n.y == y) {
return true;
} else {
return false;
}
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}