I am trying to use hashtable and when trying to search for an object,I do not see the object, but I can see it if I print it.
Node Class:
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)+")";
}
}
Main Class:
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));
}
}
I am getting NULL when I do the print line. Any idea why ?
You need to override and implement the
equalsmethod in your Node class. The default implementation fromjava.lang.Objectonly compares equality of references, which is not suitable in your case.HashMap’s rely on proper implementation of both
equalsandhashCodemethod in order to operate correctly. You should implement anequalsmethod that reflects the objects logic. Something like:You might also want to implement a
hashCode()method on yourNodeobject.