PriorityQueue 實現 Queue 接口,內部基於堆結構,元素按優先級排序而非先進先出。無 Comparator 時按自然順序 (數字小優先、字符串按字典序)。
Queue<Integer> queue = new PriorityQueue<>(10, new Comparator<Integer>() {
@Override
public int compare(Integer i, Integer j) {
// 奇數在左(優先),偶數在右
int result = i % 2 - j % 2;
if (result == 0) {
// 同奇偶性:大數在左(優先)
result = i - j;
}
return result;
}
});
for (int i = 0; i < 10; i++) queue.offer(i);
for (int i = 0; i < 10; i++) System.out.println(queue.poll());
輸出: 9 7 5 3 1 8 6 4 2 0
邏輯解析: i%2 - j%2 使奇數 (1) 小於偶數 (0) → 奇數優先。同類時 i-j 使大數優先 (因小數在前)。
// 交換參數位置:compare(Integer j, Integer i)
int result = i % 2 - j % 2; // 邏輯不變
if (result == 0) result = i - j;
return result;
輸出變為:0 2 4 6 8 1 3 5 7 9 (偶數優先、小數優先)。
PriorityQueue 非線程安全,多線程環境用 PriorityBlockingQueue。null 元素。poll() 獲取有序序列。