java 集合排序

第一種方式直接實現Comparator接口


public class ComparatorPlayerItem implements Comparator<PlayerItem> {
public int compare(PlayerItem playerItem1, PlayerItem playerItem2) {
Item item1 = playerItem1.getItem();
Item item2 = playerItem2.getItem();
//默認是按從小到大序,前加負號表示從大到小排序
return -(item1.getLevel() - item2.getLevel());
}
}


使用
Collections.sort(objs,new ComparatorPlayerItem());


第二種方式

PlayerItem實現Comparable接口中的比較方法。

這兩種方式個人比較喜歡第一種方式,侵入相當小,重用度高。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章