java - 在 Java 中对自定义数组列表进行排序

标签 java sorting

根据 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。它只需为正数、零或负数即可表示顺序。因此,我认为返回 xscore 的差异会更清楚。

附带说明一下,根据 Java 中的命名约定,类名应以大写字母开头,因此您的类 match 应命名为 Match

关于java - 在 Java 中对自定义数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15713812/

相关文章:

java - 如何将一个具体方法作为参数传递给另一个具体方法

java - 迁移到 JDK 11 + JavaFX 11 时出现 RuntimeException

java - 在一月一日使用 DateTimeFormatter 会导致年份值无效

python - 同时按行和列降序对 Dataframe 进行排序

javascript - Array.prototype.sort "[compares] strings in UTF-16 code units order"是什么意思?

java - 状态模式和封装

java - vector 始终具有相同的结果

java - 默认情况下,即使在启用 Fielddata 后,文本字段上的 Fielddata 也是禁用的

c++ - 使用基于此标志的条件语句是否比添加更多代码行更有效?

java - 对两个整数的 ArrayList 进行排序