如何排序对象的ArrayList [英] How to sort Arraylist of objects
问题描述
我有ArrayList中,这containst橄榄球队(班队)。球队有观点,我想通过点数对它们进行排序。
I have ArrayList, which containst football teams (class Team). Teams have points and i want to sort them by number of points.
public class Team {
private int points;
private String name;
public Team(String n)
{
name = n;
}
public int getPoints
{
return points;
}
public void addPoints(boolean win)
{
if (win==true)
{
points = points + 3;
}
else if (win==false)
{
points = points + 1;
}
}
//...
}
主类:
List<Team> lteams = new ArrayList<Team>;
lteams.add(new Team("FC Barcelona"));
lteams.add(new Team("Arsenal FC"));
lteams.add(new Team("Chelsea"));
//then adding 3 points to Chelsea and 1 point to Arsenal
lteams.get(2).addPoints(true);
lteams.get(1).addPoints(false);
//And want sort teams by points (first index with most points).
我做比较。
public class MyComparator implements Comparator<Team> {
@Override
public int compare(Team o1, Team o2) {
if (o1.getPoints() > o2.getPoints())
{
return 1;
}
else if (o1.getPoints() < o2.getPoints())
{
return -1;
}
return 0;
}
}
现在我想用它(在主类)
now I wanna use it (in main class)
Colections.sort(lteams, new MyComparator());
我要见:
- 切尔西
- 阿森纳
- 巴塞罗那
不过,这并不排序。
推荐答案
来源:<一个href=\"http://stackoverflow.com/questions/2535124/how-to-sort-an-arraylist-of-objects-by-a-property\">Here
您可以使用<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29\"><$c$c>Collections.sort$c$c>使用自定义的<$c$c>Comparator<Team>$c$c>.
class Team {
public final int points;
// ...
};
List<Team> players = // ...
Collections.sort(players, new Comparator<Team>() {
@Override public int compare(Team p1, Team p2) {
return p1.points- p2.points;
}
});
另外,你可以让团队实施
<$c$c>Comparable<Team>$c$c>.这个定义的的的自然所有的团队
对象排序。使用比较
是在不同的实现更加灵活的可以按姓名,年龄等订购。
Alternatively, you can make Team implements
Comparable<Team>
. This defines the natural ordering for all Team
objects. Using a Comparator
is more flexible in that different implementations can order by name, age, etc.
有关完整性,我要告诫大家,回报o1.f - o2.f
比较逐减快捷方式必须慎用由于可能溢出(读有效的Java第二版:第12项:考虑实施可比
的)。 presumably曲棍球不是一个的运动,一名球员能够进球的金额,将导致问题=)
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 =)
- Java Integer: what is faster comparison or subtraction?
这篇关于如何排序对象的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!