Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用比较器对数组进行排序?_Java - Fatal编程技术网

Java 如何使用比较器对数组进行排序?

Java 如何使用比较器对数组进行排序?,java,Java,我有一个像这样的数组 ArrayList<footballClub> newClub = new ArrayList<footballClub>(); 这是不对的,但我不知道该怎么做。在Java约定中,类的名称是这样的。因此,对于这个答案的其余部分,我将把你们的班级称为足球俱乐部 首先,必须编写一个comparator类。下面的代码段假定您将该类放入另一个类中。如果它将成为顶级类,请从第一行中删除static static class DescendingByPoint

我有一个像这样的数组

ArrayList<footballClub> newClub = new ArrayList<footballClub>();

这是不对的,但我不知道该怎么做。

在Java约定中,类的名称是这样的。因此,对于这个答案的其余部分,我将把你们的班级称为
足球俱乐部

首先,必须编写一个comparator类。下面的代码段假定您将该类放入另一个类中。如果它将成为顶级类,请从第一行中删除
static

static class DescendingByPointsComparator implements Comparator<FootballClub> {
    @Override
    public int compare(FootballClub lhs, FootballClub rhs) {
        return Integer.compare(rhs.getPoints(), lhs.getPoints());
    }
}

您可以通过以下方式轻松完成:


Collections.sort(newClub,Collections.reverseOrder())

如果您不想显示代码,那么我们无法告诉您如何改进或修复代码。你必须找到有权查看你的代码的人的帮助,或者阅读几十个问题和教程,说明如何做你想做的事情。您的代码甚至还没有编译,而且您似乎还不了解如何调用构造函数,因此我将首先开始学习基础知识。这将假定
FootballClub
实现
Comparable
:-)
static class DescendingByPointsComparator implements Comparator<FootballClub> {
    @Override
    public int compare(FootballClub lhs, FootballClub rhs) {
        return Integer.compare(rhs.getPoints(), lhs.getPoints());
    }
}
Collections.sort(newClub, new DescendingByPointsComparator());