我试图从TreeMap获取,但即使键存在,它也会返回null.
HashCode和等式仅基于单词.可比性基于频率.
public static void main(){
TreeMap<Word,Integer> test = new TreeMap<>();
test.put(new Word("pqr",12),1);
test.put(new Word("abc",2),1);
Integer prq = test.get(new Word("pqr",1));
System.out.println(prq);
prq = test.get(new Word("pqr",12));
System.out.println(prq);
}
public class Word implements Comparable<Word>{
String word;
Integer freq;
public Word(String word, Integer freq) {
this.word = word;
this.freq = freq;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Word)) return false;
Word word1 = (Word) o;
return word.equals(word1.word);
}
@Override
public int hashCode() {
return word.hashCode();
}
@Override
public int compareTo(Word o) {
return this.freq.compareTo(o.freq);
}
}
输出就像
空值
1
解决方法:
TreeMap使用compareTo方法来确定键顺序和键相等性.
由于您的Word类在其compareTo方法中使用freq字段,因此具有相同freq的任何两个Word被视为相等.
… but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal.