Comparator 接口(interface)中的 Compare() 方法的输出是 -1、0 或 1。然后将其传递给 Collections.sort() 方法,该方法可用于以自定义方式对列表进行排序。
sort() 对compare() 方法的结果做了什么? (-1、0 或 1)
我认为我最困惑的是compare()有三个输出 负数、正数或 0)。但为什么算法不只需要其中两个呢?不可以 a=b 时的 Action 与 a>b 或 a 例如。比较两个数字 a 和 b,如果 ab,则取 b(compare() 返回 +1)。为什么算法需要区分 a
例如。
class ReverseAlphabeticalComparator implements Comparator<Integer> {
@Override
public int compare(Integer i1, Integer i2) {
if(i1 > i2) {
return 1;
}
else if(i1 < i2) {
return -1;
}
return 0;
}
class App {
public static void main(String[] args) {
List<Integer> animals = new ArrayList<Integer>();
animals.add(6);
animals.add(2);
animals.add(4);
animals.add(7);
animals.add(8);
animals.add(3);
Collections.sort(numbers, new ReverseNumericalComparator());
for(String numbers: numbers) {
System.out.println(numbers); //Prints numbers in reverse eg. 8,7,6,4,3,2
}
}
}
最佳答案
What does sort() do with the result of the compare() method though?
sort
比较一系列元素对,并根据 compare
的结果,查看该对中的元素是否应该交换。
此外,compare
的结果不必是 -1
0
和 1
。来自 documentation
Returns a
negative
integer,zero
, or apositive
integer as the first argument is
less than, equal to, or greater than the second.
关于java - 'Collections.sort()'如何使用 'compare()'方法的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25297412/