I have the following Node
object:
private class Node implements Comparable<Node>(){ private String guid(); ... public boolean equals(Node o){ return (this == o); } public int hashCode(){ return guid.hashCode(); } public int compareTo(Node o){ return (this.hashCode() - o.hashCode()); } ... }
And I use it in the following TreeMap
:
TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>();
Now the tree map is used in a class called Graph
to store nodes that are currently on the graph, as well as a set of their edges (from the Edge
class). My problem is when I try to execute:
public containsNode(n){ for (Node x : nodes.keySet()) { System.out.println("HASH CODE: "); System.out.print(x.hashCode() == n.hashCode()); System.out.println("EQUALS: "); System.out.print(x.equals(n)); System.out.println("CONTAINS: "); System.out.print(nodes.containsKey(n)); System.out.println("N: " + n); System.out.println("X: " + x); System.out.println("COMPARES: "); System.out.println(n.compareTo(x)); } }
I sometimes get the following:
HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo COMPARE: 0
Does anyone have an idea what I'm doing wrong? I'm still new to all of this, so I apologize in advance if I miss something simple (I know that hashCode()
doesn't matter for TreeMap
, but I decided to enable it).
edit1: added information about compareTo()
method.
source share