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.
            Asked
            
        
        
            Active
            
        
            Viewed 2,177 times
        
    -2
            
            
        - 
                    Create a custom `Comparator` or implement `Comparable`. – Elliott Frisch Feb 13 '17 at 05:13
 - 
                    2Please add your code what you have tried so far. – Gaurav Jeswani Feb 13 '17 at 05:13
 - 
                    Hold objects in TreeSet, pass comparator to TreeSet constructor and it will maintain order for you – light_keeper Feb 13 '17 at 05:34
 
2 Answers
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