TreeMap.get() return Null 偶数键存在 [英] TreeMap.get() return Null even key exists
问题描述
我试图从 TreeMap 获取,但即使键存在它也返回 null.HashCode 和 eqauls 仅基于单词.可比性基于频率.
I am trying to get from TreeMap but it return null even the key exist. HashCode and eqauls is based on word only. Comparable is based on freqency.
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
推荐答案
在您的 compareTo
方法中,它正在比较频率.因此,如果频率相同,它将相等.
In your compareTo
method it is comparing the frequency. So if the frequency is same it will be equal.
比较你可以使用的词
return this.word.compareTo(o.word);
或者比较你可以使用的词和频率
or to compare both word and frequency you can use
return this.word.compareTo((o.word)) * this.freq.compareTo(o.freq);
编辑
现在您需要使用频率进行排序,因此您可以使用 Comparator
而不是使用可比较.使用上述比较器创建 Map.并使用您以前的比较器进行排序.
Now as you need to sort using the frequency so instead of using comparable you can use Comparator
. Use the above comparators to create the Map. And use your previous comprator to sort.
在创建时
TreeMap<Word, Integer> test = new TreeMap<Word, Integer>(
new Comparator<Word>() {
public int compare(Word word, Word o) {
return word.word.compareTo((o.word));
}
});
并且在排序时
Collections.sort(new LinkedList(test.keySet()), new Comparator<Word>() {
public int compare(Word word, Word o) {
return word.freq.compareTo((o.freq));
}
});
这篇关于TreeMap.get() return Null 偶数键存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!