Queue概述
队列(First Input First Output),简称FIFO,具有先进先出特点。队列是一种特殊的线性表结构,只能在队列的前端进行数据的查看、删除操作,队列的末端进行数据的插入操作。LinkedList是Queue的一个实现类,因此可以将LinkedList作为一个Queue进行相关使用。
1.Queue中常见方法
1.1 add()与offer()添加元素方法
- 方法介绍
方法名称 | 功能描述 |
---|---|
boolean add(E e) | 插入指定元素为该队列是否有可能立即这样做不违反容量限制 |
boolean offer(E e) | 在不违反容量限制的情况下,将指定的元素插入到队列中 |
- 案例演示
//构建队列
Queue<String> queue = new LinkedList<>();
//添加元素:add(E e)将元素插入到当前队列中
queue.add("王大锤");
System.out.println("add以后结果:" + queue);
//添加元素:offer(E e)将元素插入到当前队列中
queue.offer("高圆圆");
queue.offer("佟丽娅");
queue.offer("马哥");
System.out.println("offer以后结果:" + queue);
注意:add(E e)与offer(E e)方法的区别:若操作的队列存在一个大小限制,即队列已经满队时,使用add方法将会抛出unchecked异常添加元素,此时add方法将不再适用,而采用offer方法将返回false,不对程序产生相关影响。
1.2 element()与peek()查看元素方法
- 方法介绍
方法名称 | 功能描述 |
---|---|
E element() | 检索,但不删除此队列的头 |
E peek() | 检索,但不删除,这个队列头,或返回 null如果队列为空 |
- 案例演示
Queue<String> queue = new LinkedList<>();
//添加元素:offer将元素插入到当前队列中
queue.offer("高圆圆");
queue.offer("佟丽娅");
queue.offer("马哥");
System.out.println("offer以后结果:" + queue);
//E peek()测试:检索但不删除队列的头部元素
System.out.println("peek头元素:" + queue.peek());
//E element()检索但不删除当前队列的头部元素。当头部元素为null,会报异常
System.out.println("element头元素:" + queue.element());
注意:peek()与element()方法区别:当队列为空的过程中,若使用element()方法查看头部元素时,程序将抛出 NoSuchElementException 异常,此时element方法不在适用,应该使用peek()方法查看头部元素,当队列为空时将会返回null,注意观察throws后的内容(if this queue is empty)
element() 方法源码解析
/**
* Retrieves, but does not remove, the head of this queue. This method
* differs from {@link #peek peek} only in that it throws an exception
* if this queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*
*/
E element();
1.3 remove()与poll()删除元素方法
- 方法介绍
方法名称 | 功能描述 |
---|---|
E remove( ) | 检索和删除此队列的头 |
E poll( ) | 检索并移除此队列的头,或返回 null如果队列为空 |
- 案例演示
Queue<String> queue = new LinkedList<>();
//添加元素:offer将元素插入到当前队列中
queue.offer("高圆圆");
queue.offer("佟丽娅");
queue.offer("马哥");
//获取头部元素并删除
System.out.println("poll头元素:" + queue.poll());
System.out.println("remove头元素:" + queue.remove());
注意:poll()与remove()方法区别:当队列为空的过程中,若使用remove()方法删除头部元素时,将抛出 NoSuchElementException 异常,此时remove( )方法不在适用,应该使用poll( )方法删除头部元素,当队列为空时将会返回null,注意观察throws后的内容(if this queue is empty)
remove() 方法源码解析
/**
* Retrieves and removes the head of this queue. This method differs
* from {@link #poll poll} only in that it throws an exception if this
* queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E remove();
谢谢大家的阅读,我会继续努力提高我的相关技术……
版权声明:本文为weixin_47891374原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。