我试图从TreeMap获取,但即使键存在,它也会返回null.
HashCode和等式仅基于单词.可比性基于频率.
public static void main(){
TreeMap 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{
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