Equals()结果一致,但TreeMap.containsKey()结果不一致 [英] Consistent Equals() results, but inconsistent TreeMap.containsKey() result
问题描述
我有以下对象 Node
:
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());
}
...
}
然后在以下 TreeMap
中使用它:
TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>();
现在,树图用于名为 Graph的类
来存储当前在图中的节点及其一组边缘(来自类 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);
System.out.println("COMPARES: ");
System.out.println(n.compareTo(x));
}
}
我有时会得到以下信息:
I sometimes get the following:
哈希码:true等于:true包含:
false N:foo X:foo COMPARES:0
HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo COMPARES: 0
有人知道我在做什么错吗?我对这一切还是陌生的,所以如果我忽略了一些简单的事情,我会事先道歉(我知道 hashCode()
对<$ c $来说并不重要c> TreeMap ,但我想我会把它包括在内。)
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).
edit1:添加了 compareTo()
方法信息。
edit1: added compareTo()
method information.
推荐答案
这里有些错误。
- 您尚未覆盖
Object.equals
。使用@Override public boolean equals(Object obj)
。 -
compareTo中可能存在整数溢出错误
。这可能是导致此特定错误的原因。 -
compareTo
方法声称,如果哈希值相等,则两个实例相等代码碰巧匹配(可能是很难捕获的错误,如果没有代码审查)。
- You have not overriden
Object.equals
. Use@Override public boolean equals(Object obj)
. - There is a potential integer overflow error in
compareTo
. This is probably the cause of this particular error. It will upset the sorting, and hence the search may well not succeed. - The
compareTo
method claims two instances are equal if the hash code happens to match (could be a difficult error to catch, without code review).
有关整数溢出问题,请参见问题为什么我的简单比较器损坏了?
For integer overflow issue, see question Why is my simple comparator broken?
这篇关于Equals()结果一致,但TreeMap.containsKey()结果不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!