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

java的優先順序佇列PriorityQueue

技術標籤:刷題筆記javaPriorityQueue

  1. 介紹
    Java中PriorityQueue通過二叉小頂堆實現,可以用一棵完全二叉樹表示。
    一個基於優先順序堆的無界優先順序佇列。優先順序佇列的元素按照其自然順序進行排序,或者根據構造佇列時提供的 Comparator 進行排序,具體取決於所使用的構造方法。優先順序佇列不允許使用 null 元素。依靠自然順序的優先順序佇列還不允許插入不可比較的物件(這樣做可能導致 ClassCastException)。

  2. 構造方法:

  1. PriorityQueue() :使用預設的初始容量(11)建立一個優先順序佇列,並按其自然順序進行排序
  2. PriorityQueue(int initialCapacity, Comparator<? super E> comparator) 使用指定的初始容量建立一個 PriorityQueue,並根據指定的比較器對元素進行排序。

舉例:

PriorityQueue<Integer> q = new PriorityQueue<>();
PriorityQueue<Integer> q = new PriorityQueue<>(11,new Comparator<Integer>(){
	@Override
	public int compare(Integer o1,Integer o2){
		return o2 - o1;//逆序
	}
});
或者寫成Lambda表示式的形式
PriorityQueue<Integer> q = new PriorityQueue
<>((a,b)->b-a);
  1. 方法摘要
  1. boolean add(E e) 將指定的元素插入此優先順序佇列。
  2. boolean offer(E e) 將指定的元素插入此優先順序佇列。
  3. E peek() 獲取但不移除此佇列的頭;如果此佇列為空,則返回 null。
  4. E poll() 獲取並移除此佇列的頭,如果此佇列為空,則返回 null。
  5. int size() 返回此 collection 中的元素數。
  6. void clear() 從此優先順序佇列中移除所有元素。
  7. boolean contains(Object o) 如果此佇列包含指定的元素,則返回 true。

舉例:

public static
void main(String[] args) { PriorityQueue<Integer> q = new PriorityQueue<>(); q.add(1); q.add(3); q.offer(2); q.offer(4); System.out.println("優先順序佇列的大小"+q.size()); System.out.println("優先順序佇列的頂部"+q.peek()); System.out.println("遍歷優先佇列"); Iterator<Integer> iter = q.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } System.out.println("獲取優先順序佇列的頂部並彈出"+q.poll()); }

在這裡插入圖片描述