java - 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
解决方案
规则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
有了这5
before/after
条规则,顺序是4 34 23 15
哪个是
Reverse Lexical Order
(词法因为使用String
,反向因为比较第二到第一)
一个案例的详细信息
- 该
sort
方法将比较4
and34
,所以first=4
andsecond=34
- 你计算
"344".compareTo("434")
,因为 344 在 434 之前是你得到 -1 的词法顺序 - 因为方法会记得
-1
是之前sort
4
34
推荐阅读
- python - 初学者网页抓取代码迭代问题
- realm-list - 删除列表中的类
在领域迁移期间 - palantir-foundry - 如何在不使用 tranform 或 tranform_df 的情况下在 palantir Foundry 中导入单个数据集
- reactjs - react-firebaseui StyledFirebaseAuth 没有被编译
- visual-studio-code - 在vscode中如何向状态栏添加多个选项
- php - 如何在laravel中获取总和并分离每个ID的总数
- json - 谷歌识别的 JSON LD 格式的 Schema.org,但在网站控制台中显示错误
- compiler-errors - 为什么我的代码在混音时显示编译错误?
- sequelize.js - 为什么 Sequelize 为每个查询创建新连接?
- python - 将xml写入其中时如何删除数据框中的新行?