一、compare方法
一般用在优先级队列和重写Arrays.sort中,新建比较器,重写compare方法
1.1 优先级队列中使用(比较器后一个元素为大的)
例如:使用小顶堆找最大TopK就构造了
queue = new PriorityQueue<>(new Comparator<Integer>() { // 默认从小到大
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2; // 后一个o2大于前面的o1,所以是顺序排列
}
});
1.2 Arrays.sort()中使用(也是后一个参数是较大的)
Arrays.sort(articleRecords, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
for (int i = 0; i < 6; i++) {
if (o1[i] - o2[i] != 0) {
return o2[i] - o1[i];
}
}
return 0;
}
});
二、conpareTo方法
实例:
public class Test {
public static void main(String[] args) {
Integer x = 5;
System.out.println(x.compareTo(3));
System.out.println(x.compareTo(5));
System.out.println(x.compareTo(7));
}
}
输出:
解释:
返回值
- 如果指定的数
x大于参数
返回 1。 - 如果指定的数
x等于参数
返回0。 - 如果指定的数
x小于参数
返回 -1。