私はJavaアプリケーションを開発していて、TreeMapの使用は初めてです。プログラムは、テキストファイル内の各単語の出現回数を追跡する必要があります。ただし、データをTreeMapに配置するのに問題があります。
同じ正確なコードを使用してデータをHashMapに配置すると正常に機能しますが、データを値で並べ替える必要があります。
私はこれに2日間取り組んできましたが、完全に困惑しています。アドバイスをいただければ幸いです。
問題を実証するために、小さなサンプルコードセットを考案しました。
品詞:
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;
}
}
}