以下程序将如何工作?
How the following program will work?
我正在尝试使用小数点后第二位对数字 56、67、94、10 进行排序。实际上我不明白返回 1 或 -1 会做什么。
Collections.sort(arr, new Comparator<Integer>() {
public int compare(Integer t1, Integer t2) {
//System.out.print(" "+t1+" "+t2);
if (t1 % 10 > t2 % 10) {
return 1;
}
return -1;
}
});
当该数字相等时,您需要return归零。
最简单的方法是将比较器的主体替换为:
return Integer.compare(t1 % 10, t2 % 10);
或者,更简单:
Collections.sort(arr, Comparator.comparing(t -> t % 10));
我正在尝试使用小数点后第二位对数字 56、67、94、10 进行排序。实际上我不明白返回 1 或 -1 会做什么。
Collections.sort(arr, new Comparator<Integer>() {
public int compare(Integer t1, Integer t2) {
//System.out.print(" "+t1+" "+t2);
if (t1 % 10 > t2 % 10) {
return 1;
}
return -1;
}
});
当该数字相等时,您需要return归零。
最简单的方法是将比较器的主体替换为:
return Integer.compare(t1 % 10, t2 % 10);
或者,更简单:
Collections.sort(arr, Comparator.comparing(t -> t % 10));