0

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 ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

so, the method should be something like: Boolean equals(Node node1,Node node2), right ?
got it: public boolean equals(Object obj) { return (this == obj); }
No. It needs to be in the Node class and have the exact signature boolean equals(Object).
No public boolean equals(Object o). You can convert o to a Node object and compare it against this. this == obj will not help you, since it is the default Object.equals implementation that is causing your trouble. Shamelessly advertise on my blog post. You can translate the article using the right menu "Traduzir" combo box.
@Perception: It's not "you might also want to implement a hashCode() method"; it's "you must also implement a hashCode() method". If you override equals but not hashCode then they will be inconsistent and you will wind up with undefined behaviour from the HashMap.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.