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接口中的比較方法。
這兩種方式個人比較喜歡第一種方式,侵入相當小,重用度高。