如何对对象的 Arraylist 进行排序 [英] How to sort Arraylist of objects
问题描述
我有 ArrayList,它包含足球队(班级 Team).团队有积分,我想按积分对它们进行排序.
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());
我想看:
- 切尔西
- 阿森纳
- 巴塞罗那
但它没有排序.
推荐答案
来源:这里
您可以使用 Collections.sort
带有自定义 比较器<团队>
.
You can use Collections.sort
with a custom Comparator<Team>
.
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;
}
});
或者,您可以使团队实现
可比<团队>
.这定义了所有Team
对象的 自然顺序.使用 Comparator
更加灵活,因为不同的实现可以按名称、年龄等排序.
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.
为了完整起见,我应该注意 return o1.f - o2.f
比较减法快捷方式必须非常谨慎,因为可能会溢出(阅读:Effective Java第二版:第 12 项:考虑实现 Comparable
).大概曲棍球不是一项运动,其中球员可以进球的数量会导致问题=)
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 =)
这篇关于如何对对象的 Arraylist 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!