J'ai une ArrayList, qui contient des équipes de football (classe Team). Les équipes ont des points et je veux les trier par nombre de 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;
}
}
//...
}
Classe principale :
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).
J'ai fait mon comparatif.
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;
}
}
maintenant je veux l'utiliser (dans la classe principale)
Colections.sort(lteams, new MyComparator());
Je veux voir :
- Chelsea
- Arsenal
- Barcelone
Mais ça ne trie pas.