侧边栏壁纸
  • 累计撰写 43 篇文章
  • 累计创建 0 个标签
  • 累计收到 32 条评论

目 录CONTENT

文章目录

Java大于int类型的变量如何自定义排序

自定义排序

我们让a数组元素全部加入小顶堆排序,a[][0]小的置于堆顶,a[][0]相等的情况下,a[][1]小的置于堆顶。

当被排序元素的类型是int时,我们很好排:

import java.util.*;
import javafx.util.Pair;

class Untitled {
	public static void main(String[] args) {
		int[][] a = new int[][] {{2,1}, {2,0}, {32,2}, {5,4}, {4,0}, {1,3}};
		
		PriorityQueue<Pair<Integer, Integer>> pq = new PriorityQueue<>((o1, o2) -> o1.getKey() != o2.getKey() ? o1.getKey() - o2.getKey() : o1.getValue() - o2.getValue());
		for (int[] p: a) {
			Pair t = new Pair(p[0], p[1]);
			pq.offer(t);
		}
		while (!pq.isEmpty()) {
			Pair t = pq.poll();
			System.out.println(t.getKey() + " " + t.getValue());
		}
	}
}

/*
输出结果:
1 3
2 0
2 1
4 0
5 4
32 2
*/

但是,当被排序元素类型比int大时,需要按照下面方法排序:

import java.util.*;
import javafx.util.Pair;

class Untitled {
	public static void main(String[] args) {
		int[][] a = new int[][] {{2,1}, {2,0}, {32,2}, {5,4}, {4,0}, {1,3}};
		
    // PriorityQueue<Pair<Long, Integer>> pq = new PriorityQueue<>((o1, o2) -> o1.getKey() != o2.getKey() ? Long.compare(o1.getKey(), o2.getKey()) : o1.getValue() - o2.getValue());
    // 当 o.getKey() 的数据类型大于 int 时,按上面写法有些数据和场景会产生不可预知错误,推荐下面这种写法。
    // 即 将o1.getKey() != o2.getKey()改写为!Objects.equals(o1.getKey(), o2.getKey())
		PriorityQueue<Pair<Long, Integer>> pq = new PriorityQueue<>((o1, o2) -> !Objects.equals(o1.getKey(), o2.getKey()) ? Long.compare(o1.getKey(), o2.getKey()) : o1.getValue() - o2.getValue());
		for (int[] p: a) {
			long t1 = p[0];
			int t2 = p[1];
			Pair t = new Pair(t1, t2);
			pq.offer(t);
		}
		while (!pq.isEmpty()) {
			Pair t = pq.poll();
			System.out.println(t.getKey() + " " + t.getValue());
		}
	}
}

/*
输出结果:
1 3
2 0
2 1
4 0
5 4
32 2
*/

Preferece

0

评论区