比较器如何与 Arrays.sort 一起工作?

How does the Comparator works with Arrays.sort?

我的问题是比较器接口如何与 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"}

我按预期打印了中间结果和输出,但我无法理解它是如何works.Can有人说它是如何使用比较方法返回的整数进行排序的?

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

a.compareTo(b)

的规则
  • returns negative value : a is before b
  • returns 0 : a equal to b
  • return positive value : a 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

With these 5 before/after rules the order is 4 34 23 15

Which is Reverse Lexical Order (Lexical because use of String, reverse because compare second to first)


1例详情

  • sort方法会比较434,所以first=4second=34
  • 你计算 "344".compareTo("434"),因为 344 在 434 之前是你得到 -1
  • 的词法顺序
  • 因为 -1 sort 方法会记住 434
  • 之前