我正在開發一個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