Consistent Equals() results, but inconsistent TreeMap.containsKey() result
Posted
by smessing
on Stack Overflow
See other posts from Stack Overflow
or by smessing
Published on 2010-04-22T21:09:24Z
Indexed on
2010/04/22
21:23 UTC
Read the original article
Hit count: 351
I have the following object Node
:
private class Node implements Comparable<Node>(){
private String guid();
...
public boolean equals(Node o){
return (this == o);
}
public int hashCode(){
return guid.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 currently in the graph, along with a set of their edges (from the class Edge
). 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);
}
}
I sometimes get the following:
HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo
Anyone have an idea as to what I'm doing wrong? I'm still new to all this, so I apologize in advance if I'm overlooking something simple (I know hashCode()
doesn't really matter for TreeMap
, but I figured I'd include it).
© Stack Overflow or respective owner