通过它的实例变量的一个对象的排序的ArrayList [英] Sort ArrayList of objects through one of its instance variables
问题描述
Helllo,
我有对象(队)的ArrayList。他们的橄榄球队,我想通过自己的分给他们理清。很显然,我是完全明白的ArrayList通过它们所插入的顺序进行排序。
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.
但我有一个具有gamesWon,gamesLost,gamesTied和点数基于匹配结果Team类。
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.
感谢您。
马可波罗
推荐答案
您应该定义的 比较
这一点。
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());
这篇关于通过它的实例变量的一个对象的排序的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!