考虑一个优先队列
PriorityQueue<Integer> heap = new PriorityQueue<Integer>();
Run Code Online (Sandbox Code Playgroud)
我可以在这里以两种方式定义比较器,一种是使用lambda,另一种是使用Comparator()类
假设这两种方式对 2 个变量进行简单的整数比较,我想知道哪个变量是我们要比较的值,哪个变量包含队列中的现有值
例如:
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
System.out.println(a+" "+b);
return b-a;
}
});
Run Code Online (Sandbox Code Playgroud)
当我调用heap.add(2)后跟 a 时heap.add(3),第二个add()调用会触发compare(a,b)函数并打印a=3 & b=2,这意味着这里a有新值并且b是队列中的现有值
同样,你能告诉我下面的 lambda 表达式是否会类似地工作还是相反?
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((a,b) -> b-a);
Run Code Online (Sandbox Code Playgroud)
我知道这个问题可以用更简单的方式写出来,但我现在无法做到。
此外,这两个打印相同的值,即降序 4,3,2,1
PriorityQueue<Integer> heap2 = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
// System.out.println(a+" "+b);
return b-a;
}
});
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(
(a,b) -> b-a
);
heap.add(1);
heap.add(2);
heap.add(3);
heap.add(4);
heap2.add(1);
heap2.add(2);
heap2.add(3);
heap2.add(4);
while (!heap.isEmpty()) {
System.out.println(heap.poll()+" "+heap2.poll());
}
Run Code Online (Sandbox Code Playgroud)
您定义 的两种方法Comparator是等效的。您的 lambda 版本在编译后实际上会扩展到另一个版本,因为它Comparator是一个功能接口。
这是Comparator在Comparator接口上使用静态工厂方法来定义您的第三种更短的方法:
PriorityQueue<Integer> heap3 = new PriorityQueue<>(Comparator.reverseOrder());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51 次 |
| 最近记录: |