Java中PriorityQueue的學習

API

1.構造函數

PriorityQueue()
PriorityQueue(Collection<? extends E> c)
PriorityQueue(int initialCapacity)
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
PriorityQueue(PriorityQueue<? extends E> c)
PriorityQueue(SortedSet<? extends E> c)

2.常用功能函數

方法名 功能描述
add(E e) 添加元素
clear() 清空
contains(Object o) 檢查是否包含當前參數元素
offer(E e) 添加元素
peek() 讀取元素,(不刪除)
poll() 取出元素,(刪除)
remove(Object o) 刪除指定元素
size() 返回長度


以上參考自:https://www.cnblogs.com/demingblog/p/6485193.html


// 代碼實現
import java.util.PriorityQueue;

public class priority_queue {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PriorityQueue<Integer> q = new PriorityQueue<>();
		q.offer(3);
		q.offer(1);
		q.offer(2);
		q.offer(4);
		q.offer(5);
		System.out.println("contains 3: " + q.contains(3));
		System.out.println("remove 3: " + q.remove(3));
		System.out.println("size: " + q.size());
		while(!q.isEmpty()) {
			Integer top = q.poll();
			System.out.print(top + ", ");
		}
		System.out.println();
		
		TestNode();
	}
	
	private static class Node implements Comparable<Node> {

		int a, b;
		public Node(int a, int b) {
			this.a = a;
			this.b = b;
		}
		@Override
		public int compareTo(Node arg0) {
			// TODO Auto-generated method stub
			if(a == arg0.a) {
				return b - arg0.b;
			}
			return a - arg0.a;
		}
	}
	
	private static void TestNode() {
		PriorityQueue<Node> q = new PriorityQueue<>();
		q.offer(new Node(3, 1));
		q.offer(new Node(2, 3));
		q.offer(new Node(2, 1));
		q.offer(new Node(4, 3));
		while(!q.isEmpty()) {
			Node top = q.poll();
			System.out.print(top.a + ": " + top.b + ", ");
		}
		System.out.println();
	}

}


繼續加油~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章