前言
Queue是一个队列集合,队列是一种常用的数据结构之一,通常是指“先进先出”(FIFO)的容器。新元素插入(offer)到队列的尾部,访问元素(poll)操作会返回队列头部的元素,(队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作)。
队头(front)指向队列的第一个数据,队尾(rear)指向队列中的最后一个数据。通常,队列不允许随机访问队列中的元素。
Queue主要实现类:ArrayDeque、LinkedList、PriorityQueue。
图解Queue队列在集合中的位置:
可以看到,Queue是作为Collection接口的一个子接口,而Deque继承了Queue接口,也就是说Deque拥有更多操作。不过需要注意的是,Queue和Deque都是接口,不能实例化对象,我们可以通过其实现类实现队列的操作。
Queue 实现通常不允许插入 null 元素,尽管某些实现(如 LinkedList)并不禁止插入 null。即使在允许 null 的实现中,也不应该将 null 插入到 Queue 中,因为 null 也用作 poll 方法的一个特殊返回值,表明队列不包含元素。
简单使用
除了从Collection继承来的方法,Queue中的所有方法如下(Deque有更多的方法)
| 返回值类型 | 方法 | 描述 | |
|---|---|---|---|
| 插入 | boolean | add(E e) | 添加元素到队列中,如果不违反容量限制立即执行,若无可用可用空间会抛出异常 |
| boolean | offer(E e) | 将指定的元素插入到队列中,如果不违反容量限制立即执行 | |
| 查询 | E | element() | 返回这个队列的头,但不删除 |
| E | peek() | 返回队头元素,但不删除,若队列为空,则返回null | |
| 删除 | E | poll() | 返回这个队列的队头元素并删除队头元素,若队列为空,则返回null |
| E | remove() | 返回队头元素并删除 |
LinkedList
实例:
import org.junit.Test;import java.util.LinkedList;import java.util.Queue;public class MethodTest {@Testpublic void toTest(){Queue<String> queue = new LinkedList<>();System.out.println("当前队头元素:"+queue.peek());//null// 添加元素到队列queue.add("987"); //987将会被作为一个整体queue.offer("oo");//oo同理queue.offer("ah");queue.offer("z");System.out.println("此时队列元素为:"+queue);//[987, oo, ah, z]// 查询System.out.println("当前队头元素:"+ queue.element());//987System.out.println("当前队头元素:"+queue.peek());//987// 删除System.out.println("当前队头元素:"+queue.poll());//987 返回队头987后将987删除System.out.println("当前队头元素:"+queue.remove());//oo 返回队头oo后将oo删除// 查询System.out.println("当前队头元素:"+ queue.element()); //ah}}
输出结果:
当前队头元素:null当前队头元素:987当前队头元素:987当前队头元素:987当前队头元素:ah当前队头元素:z当前队头元素:987当前队头元素:987当前队头元素:987当前队头元素:65当前队头元素:1
PriorityQueue(优先级队列)
PriorityQueue也是一个队列的实现类,其内部储存的元素会按元素的大小顺序进行排列,因此其队头总是保持最小值。
示例:
PriorityQueue<Object> pqueue = new PriorityQueue<>();System.out.println("当前队头元素:"+pqueue.peek());//null// 添加元素到队列pqueue.add("z");pqueue.offer("aoa");pqueue.offer("abc");pqueue.offer("99");pqueue.offer("666");pqueue.offer("h");pqueue.offer("a");System.out.println("此时队列元素为:"+pqueue);//[666, 99, a, z, abc, h, aoa]//按理来说应该是[666, 99, a, abc, aoa, h, z] 先比较第一位元素再比较第二位元素......,我也没看底层源码原理,就先这样吧// 查询System.out.println("当前队头元素:"+ pqueue.element());//666System.out.println("当前队头元素:"+pqueue.peek());//666// 删除System.out.println("当前队头元素:"+pqueue.poll());//666System.out.println("当前队头元素:"+pqueue.remove());//99// 查询System.out.println("当前队头元素:"+ pqueue.element()); //a
[
](https://blog.csdn.net/qq_36804678/article/details/102837334)
