Queue
类是Collection
接口的子接口,提供插件插入,提取和检查操作。 队列通常以FIFO(先入先出)方式对元素进行排序。 LinkedList
和PriorityQueue
是JavaCollection API中队列的实现。
队列的基本操作是:
offer()
和add()
- 在队列尾部插入一个元素。poll()
和remove()
- 从队列头部删除一个元素。peek()
和element()
- 从队列头部返回一个元素。
如果任何条件失败,add()
,remove()
和element()
方法抛出异常。
如果任何条件失败,provide()
,poll()
和peek()
方法返回特殊值(null
或false
,具体取决于操作)。
文件:QueueExample.java -
package com.yiibai.tutorial;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author yiibai
*
*/
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue=new LinkedList<>();
/*Add elements to queue*/
queue.offer("One");
queue.offer("Two");
queue.offer("Three");
queue.offer("Four");
queue.offer("Five");
System.out.println("Elements in queue: "+queue);
/*Remove element from the queue*/
String removeEle=queue.poll();
System.out.println("Removed element: "+removeEle);
System.out.println("Elements in queue after poll: "+queue);
/*Get first element from the queue*/
String element=queue.peek();
System.out.println("Returned element: "+element);
System.out.println("Elements in queue after peek: "+queue);
}
}
执行上面示例代码,得到以下结果:
Elements in queue: [One Two Three Four Five]
Removed element: One
Elements in queue after poll: [Two Three Four Five]
Returned element: Two
Elements in queue after peek: [Two Three Four Five]