我正在尝试使用哈希表,当尝试搜索对象时,我看不到该对象,但如果打印它,我可以看到它。
节点类:
public class Node {
int x;
int y;
public Node() {
this.x=0;
this.y=0;
}
public Node(int x,int y) {
this.x=x;
this.y=y;
}
public String toString(){
return "(Node: x,y="+Integer.toString(x)+","+Integer.toString(y)+")";
}
}
主类:
public class GridWalk {
static Hashtable <Node, Integer> myMap;
static Stack<Node> nodes;
public static void main(String[] args) {
myMap = new Hashtable<Node,Integer>();
nodes=new Stack<Node>();
Node start=new Node(0,0);
Node new1= new Node(100,100);
myMap.put(new1,new Integer(1));
Node new2=new Node (100,100);
System.out.println("Already there ? huh: "+new2.toString()+" at "+myMap.get(new2));
}
}
当我执行打印行时,我得到 NULL。知道为什么吗?
最佳答案
您需要在 Node 类中重写并实现 equals
方法。 java.lang.Object 的默认实现仅比较引用的相等性,这不适合您的情况。
Node new1 = new Node(100, 100);
Node new2 = new Node(100, 100);
System.out.println(new1.equals(new2)); // Your current code will print false
HashMap 依赖于 equals
和 hashCode
方法的正确实现才能正确运行。您应该实现一个反射(reflect)对象逻辑的equals
方法。像这样的东西:
public boolean equals(Object o) {
if(this == o) return true;
final Node other = (Node) o;
return ((getX() == o.getX()) && (getY() == o.getY());
}
您可能还想在 Node
对象上实现 hashCode()
方法。
关于java - 在 Java 中使用 HashTable 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9651641/