Java TreeMap containsKey 总是返回 true?
我正在编写一个使用 TreeMap 接口的 Java 程序,并且遇到 containsKey 问题。即使我给 containsKey 一些我确定不在 TreeMap 中的东西,它也会返回 true。
这可能是什么原因造成的?
预先非常感谢。
--
编辑:我正在编写一个程序来计算文本文件中单词的出现次数。这些单词被解析,每个单词都是一个类的新实例。在这些类中,equals 和 hashCode 方法被重写,因为即使单词是不同的对象,也需要将它们视为相等。
“文本”字段是一个包含单词文本的字符串。
public boolean equals(Object obj){
Word temp = ((Word)obj);
return this.text.equals(temp.text);
}
public int hashCode(){
return this.text.hashCode();
}
public int compareTo (Object x) {
Word temp = ((Word)x);
if(this.text.compareTo(temp.text) < 0){
return -1;
}
else if (this.text.equals(temp.text)){
return 0;
}
else {
return 1;
}
}
I'm writing a Java program that's using the TreeMap interface, and I'm having a problem with containsKey. It is returning true even when I give containsKey something that I know for certain is not in the TreeMap.
What could be the cause of this?
Thanks so much in advance.
--
Edit: I am writing a program that counts the occurrences of words in a text file. The words are parsed and each one is a new instance of a class. In these classes, the equals and hashCode methods are overridden because the words need to be treated as equals even if they are different objects.
The field "text" a String that contains the text of the word.
public boolean equals(Object obj){
Word temp = ((Word)obj);
return this.text.equals(temp.text);
}
public int hashCode(){
return this.text.hashCode();
}
public int compareTo (Object x) {
Word temp = ((Word)x);
if(this.text.compareTo(temp.text) < 0){
return -1;
}
else if (this.text.equals(temp.text)){
return 0;
}
else {
return 1;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是,您使用的键类型的
equals
实现不正确(也可能是hashCode
),或者比较器与不一致>等于
。我的脑子里想不出任何其他原因。如果您可以制作一个简短但完整的程序来证明该问题,我们就可以确认这一点。
My guess is that you're using a key type which has an incorrect implementation of
equals
(and probablyhashCode
too), or that the comparator isn't consistent withequals
. I can't think of any other reason off the top of my head.If you can product a short but complete program demonstrating the problem, we could confirm this.