2009-12-02 105 views
1

我正在開發一個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; 
    } 
    } 
} 
+0

爲什麼要清除所有內容?請把它放回去。 –

+0

如果你正在試圖解決你在http://stackoverflow.com/questions/1828461/something-like-hashmap-but-sorted中描述的問題,那麼你的方法與TreeMap將無法工作。我建議你回到原來的問題,並按照z5h提供的答案。 – Buhb

回答

0

您的compareTo()表示如果兩個詞具有相同的計數,則兩個詞相等。因此,Treemap認爲你輸入了5個相同的對象,只保留一個。我不確定爲什麼你的計數是Word的一部分,這個數字似乎是你使用Treemap的數量。

2

你的代碼有很多問題。

首先,TreeMap按鍵排序;而不是它的價值。

其次,你可以不使用任何的一個關鍵,如果它的價值可能會改變,而在地圖或組(其中的值會影響它的equals()方法的合同)。

第三,你不應該還沒有實施的hashCode實現equals()()。

那些應該讓你成爲那裏的一部分!