问题
Helllo,
I have an ArrayList of OBJECTS (teams). They are football teams and I would like to sort them out through their points. Obviously I am fully aware ArrayLists are sorted via the order they are inserted.
But I have a TEAM class that has gamesWon, gamesLost, gamesTied and points based on a match result.
I have everything ready but figured that sorting out an ArrayList through it's points would be a cool feature to make.
I have read the Collections.sort(myArrayList) online, but this sorts based on ONE type of variable, and since I have objects within the ArrayList, I would like to sort this out.
Thank you.
Marco
回答1:
You should define a Comparator for this.
public class PointsBasedTeamComparator implements Comparator<Team> {
public int compare(Team t1, Team t2) {
//return the result of points comparison of t1 and t2
}
}
And use it as follows
Collections.sort(teams, new PointsBasedTeamComparator());
回答2:
Define a
java.util.Comparator<Team>
that implementscompareTo
with the value that you want to check.Use the sort method that accepts the
Comparator<Object>
. It will use thecompareTo
method of yourComparator
, and not the one defined inTeam
(if any).Enjoy!
来源:https://stackoverflow.com/questions/13446228/sort-arraylist-of-objects-through-one-of-its-instance-variables