我正在开发一个Java应用程序,并且是使用TreeMap的新手。程序需要跟踪文本文件中每个单词的出现次数。但是,我无法将数据放入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;
}
}
}
为什么要清除所有内容?请把它放回去。 –
如果你正在试图解决你在http://stackoverflow.com/questions/1828461/something-like-hashmap-but-sorted中描述的问题,那么你的方法与TreeMap将无法工作。我建议你回到原来的问题,并按照z5h提供的答案。 – Buhb