1. 程式人生 > 其它 >java~優先順序佇列PriorityQueue

java~優先順序佇列PriorityQueue

概念

PriorityQueue是一種支援排序的優先順序佇列,你入佇列的物件需要實現Comparable或Comparator介面,或者它本身支援自然排序,如Integer,Long這些型別(這些型別也都實現了Comparable介面)。

資料結構

優先順序佇列底層的資料結構其實是一顆二叉堆,什麼是二叉堆呢?我們來看看下面的圖(a為大頂堆,b為小頂堆)

  • 在這裡我們會發現以下特徵:
  1. 二叉堆是一個完全二叉樹
  2. 根節點總是大於左右子節點(大頂堆),或者是小於左右子節點(小頂堆)。

java程式碼例子

  • 定義一個物件,實現Comparable介面
@Data
  static class Customer implements Comparable<Customer> {
    private int id;
    private String name;

    public Customer(int i, String n) {
      this.id = i;
      this.name = n;
    }

    public int getId() {
      return id;
    }

    public String getName() {
      return name;
    }

    @Override
    public int compareTo(Customer o) {
      if (this.id < o.id) return -1; // 小於目標值,返回-1表示升序,即-1表示數值由小到大的排序
      else if (this.id == o.id) return 0;
      else return 1;
    }
  }
  • 新增測試用例
  @Test
  public void test() {
    Queue<Customer> priorityQueue = new PriorityQueue<>();
    priorityQueue.add(new Customer(1, "zhansan"));
    priorityQueue.add(new Customer(2, "lisi"));
    priorityQueue.add(new Customer(4, "wangwu"));
    while (!priorityQueue.isEmpty()) {
      Customer cust = priorityQueue.poll();
      System.out.println("Processing Customer =" + cust.toString());
    }
  }
  • 測試結果,按著id的升序出佇列
Processing Customer =PriorityQueueTest.Customer(id=1, name=zhansan)
Processing Customer =PriorityQueueTest.Customer(id=2, name=lisi)
Processing Customer =PriorityQueueTest.Customer(id=4, name=wangwu)

作者:倉儲大叔,張佔嶺,
榮譽:微軟MVP
QQ:853066980

支付寶掃一掃,為大叔打賞!