[英]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.