集合-队列-优先队列PriorityQueue
1204
2021.11.04
发布于 未知归属地

参考资料:
https://www.jianshu.com/p/999c1b628728

结构:

1.逻辑结构(完全二叉树--小跟堆)
2.物理结构(数组--二叉树的层序遍历)

特点:

1.不能存储null,抛异常
2.有序
3.线程不安全

方法:

1.创建--元素类型

a.基本类型的包装类(默认是升序)
b.自定义类(必须实现Comparator)

2.入队--add和offer

a.add调用了offer,二者等价。
b.插入null,抛异常
c.插入元素后,为了保证小根堆,要调整

3.出队--peek/element/poll/remove

a.队首:获取队首元素,但是不删除
peek--如果size=0,返回null;否则返回队首元素。
element--如果size=0,抛出异常;否则返回队首元素。

b.队首:获取队首元素,但是删除
poll--失败是,抛出异常;
remove--失败时,返回null;

4.打印(无序)

无序输出

示例

import java.util.PriorityQueue;

public class TestPriorityQueue {
    /**
     * 创建 + 入队 + 出队: 元素是基础类型的包装类(默认升序)
     */
    private static PriorityQueue create1(){
        // 创建优先队列
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(10);

        // 入队--add和offer(两者等价,add调用offer)
        try {
            priorityQueue.add(null); // crash,不能增加null
        } catch (Exception e) {
            System.out.println("add/offer exception = " + e.getMessage());
        }

        priorityQueue.add(2);
        System.out.println("priorityQueue = " + priorityQueue); // [2]

        priorityQueue.add(1);
        System.out.println("priorityQueue = " + priorityQueue); // [1, 2]

        priorityQueue.offer(6);
        System.out.println("priorityQueue = " + priorityQueue); // [1, 2, 6]

        priorityQueue.offer(3);
        System.out.println("priorityQueue = " + priorityQueue); // [1, 2, 6, 3]

        // 出队--peek/element/poll/remove
        priorityQueue.peek(); // 返回队首,不删除
        System.out.println("priorityQueue = " + priorityQueue); // [1, 2, 6, 3]

        priorityQueue.element(); // 返回队首,不删除
        System.out.println("priorityQueue = " + priorityQueue); // [1, 2, 6, 3]

        priorityQueue.poll(); // 返回队首,要删除
        System.out.println("priorityQueue = " + priorityQueue); // [2, 3, 6]

        priorityQueue.remove(); // 返回队首,要删除
        System.out.println("priorityQueue = " + priorityQueue); // [3, 6]

        return priorityQueue;
    }

    /**
     * 创建 + 入队:元素是自定义类--要求:元素实现Comparator接口
     */
    private static void create2(){

    }

    /**
     * 遍历:有序输出
     */
    private static void print() {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(10);
        priorityQueue.offer(6);
        priorityQueue.add(1);

        while (!priorityQueue.isEmpty()) {
            System.out.println(priorityQueue.poll());
        }
    }

    public static void main(String[] args) {

        create1();
        create2();
        print();
    }
}
评论 (0)