首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java PriorityQueue 優先隊列入門:自定義比較器實現奇偶排序實戰

     編輯:Java 綜合教學

Java PriorityQueue 優先隊列入門:自定義比較器實現奇偶排序實戰

核心概念

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() 獲取有序序列。
  • 默認初始容量 11,可指定初始容量減少擴容開銷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved