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
2 Answers 2
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());
Comments
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!
2 Comments
Comparator
rather than Comparable
; being Comparable
implies that the objects have a single natural order, whereas a Comparator
is just some particular way of sorting them, of which there could be several.