如何通过属性对对象的数组列表排序? [英] How to sort an arraylist of objects by a property?

查看:147
本文介绍了如何通过属性对对象的数组列表排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有 Arraylist HockeyPlayer 对象。



如果他们都有一个变量 int goalsScored ,如何排序呢?

解决方案

您可以使用 Collections.sort 与自定义 Comparator< HockeyPlayer>

  class HockeyPlayer {
public final int goalsScored;
// ...
};

List< HockeyPlayer> players = // ...

Collections.sort(players,new Comparator< HockeyPlayer>(){
@Override public int compare(HockeyPlayer p1,HockeyPlayer p2){
return p1.goalsScored - p2.goalsScored; // Ascending
}

});或者,您可以使 HockeyPlayer implements a href =http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html =nofollow noreferrer> 可比较的< HockeyPlayer> 。这为所有 HockeyPlayer 对象定义自然顺序。使用比较器更灵活,因为不同的实现可以按名称,年龄等进行排序。



/ h3>






为了完整起见,我应该注意 return由于可能的溢出,必须非常小心使用比较减法快捷方式(读取: Effective Java第2版:项目12:考虑实现 Comparable )。推测曲棍球不是一种运动,其中玩家可以导致问题的数量的目标)=)



参见




Lets say you have an Arraylist of HockeyPlayer objects.

How could you sort that if they all have a variable int goalsScored. How could you sort them by goalsScored?

解决方案

You can use Collections.sort with a custom Comparator<HockeyPlayer>.

    class HockeyPlayer {
        public final int goalsScored;
        // ...
    };

    List<HockeyPlayer> players = // ...

    Collections.sort(players, new Comparator<HockeyPlayer>() {
        @Override public int compare(HockeyPlayer p1, HockeyPlayer p2) {
            return p1.goalsScored - p2.goalsScored; // Ascending
        }

    });

Alternatively, you can make HockeyPlayer implementsComparable<HockeyPlayer>. This defines the natural ordering for all HockeyPlayer objects. Using a Comparator is more flexible in that different implementations can order by name, age, etc.

See also


For completeness, I should caution that the return o1.f - o2.f comparison-by-subtraction shortcut must be used with extreme caution due to possible overflows (read: Effective Java 2nd Edition: Item 12: Consider implementing Comparable). Presumably hockey isn't a sport where a player can score goals in the amount that would cause problems =)

See also

这篇关于如何通过属性对对象的数组列表排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆