首页 > 解决方案 > Comparator 如何与 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"}

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

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

标签: javaarrayscomparator

解决方案


规则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

有了这5before/after条规则,顺序是4 34 23 15

哪个是Reverse Lexical Order(词法因为使用String,反向因为比较第二到第一)


一个案例的详细信息

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

推荐阅读