I have a Node class which now represents a cell in a matrix. It implements the Comparable interface and overrides the equals(...) method because I'd like to store Node objects in a TreeSet<Node> set.
Unpredicted behaviour occurs at this point:
I'll explain it properly. openedNode and n are instances of Node, openedNodes is an instance of TreeSet<Node>.
The method g(Node, Node) in the first row of the code above just adds the g values of the two parameters, getG() and setG(int) are just regular get and set methods.
When execution reaches "openedNodes.add(openedNode);" sometimes it says that openedNodes already contains openedNode (but in reality, it doesn't contains it).
Then I tried this:
In this case it removes a Node from openedNodes (call it falseOpenedNode) and then adds the actual openedNode, so it finds that these two nodes are equivalent. But when I call openedNode.equals(falseOpenedNode) explicitly at this point it returns false (which is correct).
I'll show an example with concrete values if you need it.
To be able to store Node objects in a TreeSet, Node must also implement the hashCode() method in accordance with your equals() method. Here's a good article that explains how you should implement equals() and hashCode(): Java theory and practice: Hashing it out
I've written the hashCode() and equals() methods according to the article, then I've generated these methods with Eclipse but neither of the solutuions works properly It still does the same mistake.
Your compareTo() method is inconsistent with your equals() method. That is, to use a TreeSet as a Set, for all a and b where a.compareTo(b) == 0, a.equals(b) must be true.
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
First of all, TreeSet is not hash based tree, so it does not use hashcode() and equals() method to before storing the objects.
TreeSet just uses campareTo() method for this purpose. So just concentrate on your compareTo() method.
Garrett Rowe wrote:Your compareTo() method is inconsistent with your equals() method. That is, to use a TreeSet as a Set, for all a and b where a.compareTo(b) == 0, a.equals(b) must be true.
Okay, now I use HashSet instead of TreeSet and I implemented a method which selects the element with the minimal (g+h) value. I won't forget this case for sure Thank you!
Don't get me started about those stupid light bulbs.