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();
	}

}


继续加油~

猜你喜欢

转载自blog.csdn.net/yo_bc/article/details/79749560