重写此@如何重写数组。用Java排序工作?
Arrays.sort(people, (n1, n2) -> (n2[0] == n1[0])? n1[1] - n2[1] : n2[0] - n1[0]);
或
Arrays.sort(people,new Comparator<int[]>(){
@Override
public int compare(int[] n1, int[] n2){
return (n2[0] == n1[0])? n1[1] - n2[1]: n2[0] - n1[0];
}
});
两者执行相同的操作
输入:[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
输出:[[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]]
我知道代码是分组排序的,但我不知道如何排序。我同样对Java中的PriorityQueue感到困惑:
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b)-> b - a);
这个按降序排序
有人能解释一下吗?如果存在此类材料,我可以在哪里学习或阅读更多有关这些“覆盖”的信息
# 1 楼答案
这是一个巨大的飞跃,但您迟早应该了解接口、匿名类和lambda
oracle网站上有一套教程:
https://docs.oracle.com/javase/tutorial/java/IandI/index.html https://docs.oracle.com/javase/tutorial/java/javaOO/index.html
# 2 楼答案
箭头表示法是lambda函数,是同一比较器实现的缩写。这就是为什么你会看到同样的结果。这里并不是关于
@Override
,你要问的是比较器是如何工作的比较器按以下顺序排列2个对象:
因此,对于优先级队列部分,当比较器对1、4、6、3进行排序时,它会比较数组的元素,如果差值为负数,它会交换它们,例如,它会交换1和4、4和6,等等
对于问题的第一部分,您正在使用以下实现:
(n2[0] == n1[0])? n1[1] - n2[1]: n2[0] - n1[0]
对于2个大小的整数数组,将按如下方式比较数组
# 3 楼答案
^{} 方法^{} 的javadoc说:
“小于”和“大于”指的是排序顺序,而不是数值,因此,如果要对降序,则
7
是“小于”5
因此,下面显示了如何进行升序和降序排序:
但是,千万不要为此使用} 方法,或使用^{} 、^{} 、^{} 、^{} 和^{} 上的等效方法:
-
减号运算符,因为它可能导致溢出。改为使用^{下一部分是代码按2个字段排序,第一个字段降序,第二个字段升序:
在您的代码中,这是使用三元运算符完成的:
或者相反:
# 4 楼答案
来自比较器。与javadoc https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-相比
# 5 楼答案
上面的数组。排序接受2个参数。第一个是需要排序的列表,第二个是比较器。比较器是具有方法比较的功能接口。因为它是接口,所以您需要实现它(@Override表示您的实现正在重写此方法)。 方法比较允许您决定排序策略(升序、降序、blabla)
# 6 楼答案
@Override
注释只是标记子类中的方法何时重写超类中的方法。在第二个示例中,您使用的是一个名为匿名内部类的东西,您基本上是在传递一个类的实例,在您的示例Comparator
中,它有一个名为compare
的抽象方法。您正在适当地实现该方法功能,这样您就不必创建一个扩展Comparator
类等的新类您的第一个示例与第二个示例基本相同,但其语法编写起来更短,看起来更清晰,更易于阅读。第二个称为
Lambda expression