你好,
我有一个 OBJECTS(团队)的 ArrayList.他们是足球队,我想通过他们的积分来分类.显然我很清楚 ArrayLists 是按照它们插入的顺序排序的.
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.
但我有一个 TEAM 课程,其中包含 gamesWon、gamesLost、gamesTied 和基于比赛结果的积分.
But I have a TEAM class that has gamesWon, gamesLost, gamesTied and points based on a match result.
我已经准备好了一切,但我认为通过它的点对 ArrayList 进行排序将是一个很酷的功能.
I have everything ready but figured that sorting out an ArrayList through it's points would be a cool feature to make.
我已经在线阅读了 Collections.sort(myArrayList),但是这种排序基于一种类型的变量,并且由于我在 ArrayList 中有对象,我想对此进行排序.
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.
谢谢.
马可
推荐答案您应该定义一个 Comparator 为此.
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 } }并按如下方式使用
Collections.sort(teams, new PointsBasedTeamComparator());