我正在开发一个 Java 应用程序,并且刚开始使用 TreeMap。该程序需要跟踪文本文件中每个单词的出现次数。但是,我在将数据放入 TreeMap 时遇到问题。
当我使用相同的代码将数据放入 HashMap 时,它工作得很好,但我需要按值对数据进行排序。
我已经为此工作了两天,但我完全被难住了!任何建议将不胜感激。
我设计了一个小的示例代码集来演示该问题:
词类:
public class impents Comrable {
public Wo (String s) {
this.tesdxt = s;
thnt = 1;
}
public int coeTo (Object x) {
sd
if (thiunt < temp.count){
ret
return 1;
}sd
}
public void inemnt(){
this.cot++;
}
public bolean equals(Object obj){
d temp= ((ls(temp.text) &&
this.unt == temp.count;
}
public int hashCode(){
return this.tshCode() +
Integer.toSsdtring(count).hashCode();
}s
public String toString(){
return this.text;
}
}
计数类别:
public class Counts{
public Counts () { }
public iutTest(){
for(int i = 0; i < 5; i++){
sortedCoun.put(new Word("testWord #"+i), 1);
}
return sortedWordCounts.size();
}
}
比较器类:
public class Sorteparator impleWord,Integer> map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
if(!map.consKey(o1) || !map.coninsKey(o2)) {
return 0;
}
if(mapet(o1) < map.get(o2)) {
retrn ap.get(o2)) {
return 0;
} ee {
return -1;
}
}
}
最佳答案
您的代码存在很多问题。
首先,TreeMap 按其键排序;不是它的值。
其次,如果任何值在 Map 或 Set 中可能发生变化(其中值影响其 equals() 方法契约),则不得使用任何值作为键。
第三,如果没有实现 hashCode(),则不应实现 equals()。
这些应该可以帮助您实现目标!
关于java - TreeMap 只允许放入一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1830167/