How to sort Arraylist of objects

前端 未结 3 1385
星月不相逢
星月不相逢 2020-12-03 05:42

I have ArrayList, which containst football teams (class Team). Teams have points and i want to sort them by number of points.

 public class Team {
     priva         


        
3条回答
  •  日久生厌
    2020-12-03 06:17

    Source : Here

    You can use Collections.sort with a custom Comparator.

        class Team {
            public final int points;
            // ...
        };
    
        List players = // ...
    
        Collections.sort(players, new Comparator() {
            @Override public int compare(Team p1, Team p2) {
                return p1.points- p2.points;
            }
    
        });
    

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

    See also

    • Java: What is the difference between implementing Comparable and Comparator?

    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

    • Java Integer: what is faster comparison or subtraction?

提交回复
热议问题