如何通过更高或更低的数字对数组进行排序。

排列

ArrayList<TestClass> array1 = new ArrayList<>();

public class TestClass{

    public boolean type;
    public int counter;

    public TestClass(boolean type, int counter) {
        this.type = type;
        this.counter = counter;
    }

}

我试过这样做

Collections.sort(array1);

但我知道了

reason: no instance(s) of type variable(s) T exist so that TestClass conforms to Comparable<? super T>
分析解答

假设您没有任何辅助方法,您可以使用

array1.sort(Comparator.comparing(a -> a.counter));

您要求的排序顺序是reverse订单,有几种方法可以实现这一点。

你可以简单地做一个像以前那样的reverse

array1.sort(Comparator.comparing(a -> a.counter));
array1.sort(Collections.reverseOrder());

如果您不能使用Comparator.comparing,则可以执行以下操作

Collections.sort(array1, (item1, item2) -> Integer.compare(item2.counter, item1.counter));

以上陈述可以解释如下。

  • Collections.sort()Java collections framework提供。

  • 第一个参数指定需要对哪个集合进行排序。

  • 第二个参数描述了集合中的每个对象应该如何 与其他对象进行比较评估。因此,对于每对对象,在您的情况下为整数,如果第二个元素大于第一个元素,则条件返回true。这将使整个list从高到低出现