Ahsan
Ahsan

Reputation: 2982

Issues with using HashTable in Java

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 ?

Upvotes: 0

Views: 160

Answers (1)

Perception
Perception

Reputation: 80633

You need to override and implement the equals method in your Node class. The default implementation from java.lang.Object only compares equality of references, which is not suitable in your case.

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's rely on proper implementation of both equals and hashCode method in order to operate correctly. You should implement an equals method that reflects the objects logic. Something like:

public boolean equals(Object o) {
    if(this == o) return true;

    final Node other = (Node) o;
    return ((getX() == o.getX()) && (getY() == o.getY());
}

You might also want to implement a hashCode() method on your Node object.

Upvotes: 3

Related Questions