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

}


继续加油~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值