根据这篇文章,我尝试定义一个新的比较器来对包含自定义类的数组列表进行排序。我的代码如下:
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() 时,匹配列表似乎没有改变。我不知道出了什么问题。有人可以给我一些建议吗?提前致谢