比较器如何与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"}


我打印了中间结果并且输出是预期的,但我无法理解它是如何工作的。有人可以说通过使用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


隔江千里
浏览 229回答 1
1回答

智慧大石

规则&nbsp;a.compareTo(b)returns negative value&nbsp;:&nbsp;a is before breturns 0&nbsp;:&nbsp;a equal to breturn positive value&nbsp;:&nbsp;a is after b因为参数是,first, second并且您进行比较,second.compareTo(first)您将获得相反的顺序:second+first)&nbsp; &nbsp;344 first+ second&nbsp; 434 comparing : -1 >>&nbsp; &nbsp;4 is before 34(second+first)&nbsp; &nbsp;423 first+ second&nbsp; 234 comparing : 2&nbsp; >>&nbsp; 23 is after&nbsp; &nbsp;4(second+first)&nbsp; 3423 first+ second 2334 comparing : 1&nbsp; >>&nbsp; 23 is after&nbsp; 34(second+first)&nbsp; 3415 first+ second 1534 comparing : 2&nbsp; >>&nbsp; 15 is after&nbsp; 34(second+first)&nbsp; 2315 first+ second 1523 comparing : 1&nbsp; >>&nbsp; 15 is after&nbsp; 23使用这5before/after条规则,顺序是4 34 23 15这是Reverse Lexical Order(词汇,因为使用String,反向,因为与第一比较第二)一种情况的详细信息该sort方法将比较4和34,因此first=4和second=34您进行计算"344".compareTo("434"),因为344在434之前是344的词汇顺序由于-1该sort方法会记得4是前34
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java