[英]Issues with using HashTable in Java
我正在尝试使用哈希表,并且在尝试搜索对象时,我没有看到该对象,但是如果我打印它,我可以看到它。
节点类别:
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
方法的正确实现才能正常运行。 您应该实现一个反映对象逻辑的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()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.