-2

I need to constantly add new players to the data field. So I was thinking of first adding everyone to an ArrayList where the object player has two variables: name and score. Then I want to create a rank method that would deposit all of the players from my arraylist into an array and sort them from highest score to lowest. I don't know how to sort them however as this is a custom object I am trying to sort. The example I am working with is a data set of 49 players.

2 Answers2

0

You would have to implement the Comparable interface and override the compareTo method in order to do your custom comparison. More here: https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Anoop R Desai
  • 712
  • 5
  • 18
0

it seems to work for u.

public static void main(String[] args) {


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

    players.add(new Player("L", 98));
    players.add(new Player("M", 88));
    players.add(new Player("N", 90));

    System.out.println("before " + players);

    Collections.sort(players, new Comparator<Player>() {
        @Override
        public int compare(Player o1, Player o2) {
            return o1.getScore() > o2.getScore() ? -1 : 1;
        }
    });


    System.out.println("after  " + players);
}

static class Player {

    private String name;

    private double score;

    public Player(String name, double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "{" + name + ", " + score + "}";
    }
}
Rod Bate
  • 79
  • 3