1. 前言
最近在做到一个业务的时候,对排序有特殊要求,要求
a
和b
相绑定,先对a
进行降序排序,如果a
相同的情况下,需要也对b
进行降序排序,这个明显是要自定义类来实现Comparable
接口或Comparator
接口并分别重写compareTo
、compare
方法来实现,这部分我有些生疏了,故在此写出来后进行回顾
2. 实现 Comparable 接口
import java.util.Comparator;
import java.util.PriorityQueue;
class Pair implements Comparable<Pair> {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Pair other) {
// 首先根据 a 降序排序
int compareA = Integer.compare(other.a, this.a);
if (compareA != 0) {
return compareA;
}
// 如果 a 相同,则根据 b 降序排序
return Integer.compare(other.b, this.b);
}
}
public class Main {
public static void main(String[] args) {
PriorityQueue<Pair> priorityQueue = new PriorityQueue<>();
// 添加数据到优先队列中
priorityQueue.offer(new Pair(5, 10));
priorityQueue.offer(new Pair(3, 8));
priorityQueue.offer(new Pair(5, 5));
priorityQueue.offer(new Pair(7, 2));
// 取出并打印排序后的数据
while (!priorityQueue.isEmpty()) {
Pair pair = priorityQueue.poll();
System.out.println("(" + pair.a + ", " + pair.b + ")");
}
}
}
- 在这个示例中,
Pair
类实现了Comparable<Pair>
接口,并重写了compareTo
方法来定义排序规则。当比较两个Pair
对象时,首先比较它们的a
值,如果a
值不同,则直接返回比较结果(降序),如果a
值相同,则比较它们的b
值 PriorityQueue
默认是小顶堆,但因为我们重写了compareTo
方法以返回降序的结果,所以实际上它会表现出大顶堆的行为
3. 实现 Comparator 接口
import java.util.Comparator;
import java.util.PriorityQueue;
class Pair {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
// Getters for a and b (optional, but good practice)
public int getA() {
return a;
}
public int getB() {
return b;
}
}
public class Main {
public static void main(String[] args) {
// 创建一个Comparator匿名内部类来定义排序规则
Comparator<Pair> pairComparator = new Comparator<Pair>() {
@Override
public int compare(Pair p1, Pair p2) {
// 首先根据 a 降序排序
int compareA = Integer.compare(p2.getA(), p1.getA());
if (compareA != 0) {
return compareA;
}
// 如果 a 相同,则根据 b 降序排序
return Integer.compare(p2.getB(), p1.getB());
}
};
// 使用Comparator创建PriorityQueue
PriorityQueue<Pair> priorityQueue = new PriorityQueue<>(pairComparator);
// 添加数据到优先队列中
priorityQueue.offer(new Pair(5, 10));
priorityQueue.offer(new Pair(3, 8));
priorityQueue.offer(new Pair(5, 5));
priorityQueue.offer(new Pair(7, 2));
// 取出并打印排序后的数据
while (!priorityQueue.isEmpty()) {
Pair pair = priorityQueue.poll();
System.out.println("(" + pair.getA() + ", " + pair.getB() + ")");
}
}
}