tags:

views:

298

answers:

4

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?

+4  A: 

Write a custom Comparator to do the job.

duffymo
+2  A: 

Use a generic Comparator like the Bean Comparator.

camickr
A: 

Java has a set of sort() methods for this sort of thing. See Collections.sort (and Comparable) for details.

CWF
+5  A: 

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;
        }

    });

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

polygenelubricants
Do self-goals count as negatives? Because if `goalsScored` is strictly positive, then the subtraction trick is fine.
polygenelubricants