我有 ArrayList,其中包含足球队(Team 类)。团队有积分,我想按积分数对它们进行排序。
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;
}
}
现在我想使用它(在主课中)
Colections.sort(lteams, new MyComparator());
我想看看:
- 切尔西
- 兵工厂
- 巴塞罗那
但它没有排序。