0

I have this user class

public class User {

public String userName;
public int highScore = 0;

public static ArrayList<User> userList = new ArrayList<User>(5);

public User(String name, int score) {
    this.userName = name;
    this.highScore = score;
    userList.add(this);

    Collections.sort(userList, new Comparator<User>() {
        @Override
        public int compare(User lhs, User rhs) {
            return lhs.highScore-rhs.highScore;
        }

    });

}

}

The User object has properties name and score.i want to sort my list on the basis of score of the user.

Mukul
  • 141
  • 1
  • 11

2 Answers2

3
    java.util.Collections.sort(userList, new Comparator<User>(){
        @Override
        public int compare(User lhs, User rhs) {
            return lhs.getScore() - rhs.getScore();
        }

    });
Taky
  • 5,284
  • 1
  • 20
  • 29
0

Create an object that implements Comparator:

http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html

This essentially implements a comparison between two objects. From this, you can use automatic sort methods.

public class UserComparator implements Comparator {
    public boolean compare(Object object1, Object object2) {
        return ... \\ result of comparison
    }
}
public static ArrayList<User> userList = new ArrayList<User>(5);

Collections.sort(usersList, new UserComparator());

the return value is an int.

0 if object1 equals object2
a negative int if object1 < object2
a positive int if object1 > object2
mjshaw
  • 401
  • 2
  • 7