开发者

Java TreeMap containsKey invariably returning true?

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, t开发者_StackOverflow中文版he 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;
   }
} 


My guess is that you're using a key type which has an incorrect implementation of equals (and probably hashCode too), or that the comparator isn't consistent with equals. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜