比较器如何与Arrays.sort一起使用?

时间:2018-07-04 08:05:03

标签: java arrays comparator

我的问题是比较器接口如何与arrays.sort方法一起使用? 例如:

  Arrays.sort(arr, new Comparator<String>(){
        public int compare(String first, String second){
            System.out.println("Comparator : (second+first)  "+(second+first)+" first+ second "+(first+second)+" comparing : "+(second+first).compareTo(first+second));
            return (second+first).compareTo(first+second);
        }
    });

输入

arr = {"34","4","23","15"}

因此,基本上,以上代码段是将数组排列为最大的数字。

输出将为{"4","34","23","15"}

我打印了中间结果并且输出是预期的,但是我无法理解它是如何工作的。有人可以说通过使用compare方法返回的整数对它进行排序吗?

Comparator : (second+first)  344 first+ second 434 comparing : -1
Comparator : (second+first)  423 first+ second 234 comparing : 2 
Comparator : (second+first)  3423 first+ second 2334 comparing : 1 
Comparator : (second+first)  3415 first+ second 1534 comparing : 2
Comparator : (second+first)  2315 first+ second 1523 comparing : 1

1 个答案:

答案 0 :(得分:3)

a.compareTo(b)的规则

  • returns negative valuea is before b
  • returns 0a equal to b
  • return positive valuea is after b

因为参数为first, second,并且您像second.compareTo(first)那样进行比较,所以会得到相反的顺序:

(second+first)   344 first+ second  434 comparing : -1 >>   4 is before 34
(second+first)   423 first+ second  234 comparing : 2  >>  23 is after   4
(second+first)  3423 first+ second 2334 comparing : 1  >>  23 is after  34
(second+first)  3415 first+ second 1534 comparing : 2  >>  15 is after  34
(second+first)  2315 first+ second 1523 comparing : 1  >>  15 is after  23
  

使用这5条before/after规则,顺序为4 34 23 15

     

哪个是 Reverse Lexical Order (之所以用词法,是因为使用了String,反之则是因为倒数第二)。


一种情况的详细信息

  • sort方法将比较434,因此first=4second=34
  • 您计算"344".compareTo("434"),因为344在434之前是-1的词汇顺序
  • 由于-1sort方法将记住434之前