根据 this post ,我尝试定义一个新的比较器来对包含自定义类的数组列表进行排序。我的代码如下:
public class mainClass{
public class match {
/*I defined a new class to hold some data points*/
public int x;
public int y;
public int score;
public match(){
/*initialize values of match if needed*/
}
}
public ArrayList<match> matchList=new ArrayList<match>(); //the arraylist that holds data
/*code that fills the list with matches*/
/*the following method is supposed to sort the matchlist. a match with higher score is bigger, and with the same score, a match with bigger x is bigger*/
public void sortMatchlist(){
Collections.sort(this.matchList,new Comparator<match>(){
@Override
public int compare(match o1, match o2) {
if(o1.score>o2.score) return 1;
else if(o1.score==o2.score){
if(o1.x>o2.x) return 1;
else return 0;
}
else return 0;
}
});
}
然而,当我在 main 中调用 sortMatchList() 时,匹配列表似乎没有变化。我不知道出了什么问题。有人可以给我一些建议吗?提前致谢
最佳答案
这应该可以完成工作:
if (o1.score == o2.score) {
return o1.x - o2.x;
} else {
return o1.score - o2.score;
}
compare
的输出不必是 1、-1 或 0。它只需为正数、零或负数即可表示顺序。因此,我认为返回 x
或 score
的差异会更清楚。
附带说明一下,根据 Java 中的命名约定,类名应以大写字母开头,因此您的类 match
应命名为 Match
。
关于java - 在 Java 中对自定义数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15713812/