自定義集合比較
Collections.sort(sortList, WordCounter.CASE_INSENSITIVE_ORDER);
集合類中可以傳入比較器作爲排序規則,需要比較的類中添加自定義比較方法,如下定義:
使用集合第二參數比較器,需要在類中聲明該比較器
Class WordCounter{
public static final Comparator<wordCounter> CASE_INSENSITIVE_ORDER = new Comparator<wordCounter>() {
@Override
public int compare(wordCounter o1, wordCounter o2) {
return o1.word.compareToIgnoreCase(o2.word);//這裏寫兩個類的自定義比較規則
}
};
private String word;
private int id;
public WordCounter(int id,String word){
this.word=word;
this.id=id;
}
}