Sort a list that contains a custom class

so I'm currently doing an exercise for a college that has a few optional parts (because we haven't done this in the class yet), one of them is to use lists instead of arrays (so that it will be a variable size) and another prints the list, sorted by points (I will get to that)

So, I have a Player.java class that looks like this.

public class Player {
String name;
String password;
int chips;
int points;
public Player (String n, String pw, int c, int p) {
    name = n;
    password = pw;
    chips = c;
    points = p;
}
public String getName () {
    return name;
}
public void setName (String n) {
    name = n;
}
public void setPW (String pw) {
    password = pw;
}
public String getPW () {
    return password;
}
public void setChips (int c) {
    chips = c;
}
public int getChips () {
    return chips;
}
public void setPoints (int p) {
    points = p;
}
public int getPoints () {
    return points;
}

}

Pretty simple, then I create a List with this (in another class):

List<Player> lplayer = new ArrayList<Player>(); 

Adding players with this:

lplayer.add(new Player(n,pw,c,p))`

And finally, after reading their statistics:

public int search_Player (String n) {
    String name;
    int i = 0;
    boolean found = false;
    while ((i <= tp) && (!found)) {
        name = lplayer.get(i).getName();
        if (name.equals(n)) {
            found = true;
        }
        i++;
    }
    return (found == true) ? i-1 : -1;
}
public Player show_Player (int i) {
    return lplayer.get(i);
}
public void list_Players() {
    Collections.sort(lplayer);
    int i2;
    if (tp > 0) { // variable which contains number of total players
        for (int i = 0;i<tp;i++) {
            i2 = i+1;
            System.out.println ("\n"+i2+". "+lplayer.get(i).getName()+" [CHIPS: "+lplayer.get(i).getChips()+" - POINTS: "+lplayer.get(i).getPoints()+"]");
        }
    }
    else {
        System.out.println ("There are no players yet.");
    }
}

. , list_Players, , . , ( ).

, java, , , .

, Collections.sort(list), , , .

!

+5
2

public static <T> void sort(List<T> list, Comparator<? super T> c) Collections - ( ) - !

: , . ,

Collections.sort(list, new Comparator<Player>() {
    int compare(Player left, Player right)  {
        return left.getPoints() - right.getPoints(); // The order depends on the direction of sorting.
    }
});

!

+7

Collections.sort(list) . , Java. " " ( ), , .

Collections.sort(list) , Comparaple. , , .

, , , , . ( ) , (1, 5, 2, 7...). .

+1

All Articles