我有这个用户类
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;
}
});
}
}
User对象具有属性名称和得分。我想根据用户的得分对列表进行排序。
答案 0 :(得分:3)
java.util.Collections.sort(userList, new Comparator<User>(){
@Override
public int compare(User lhs, User rhs) {
return lhs.getScore() - rhs.getScore();
}
});
答案 1 :(得分:0)
创建一个实现Comparator的对象:
http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html
这基本上实现了两个对象之间的比较。从这里,您可以使用自动排序方法。
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());
返回值为int。
0 if object1 equals object2
a negative int if object1 < object2
a positive int if object1 > object2