Queue接口

基本概念

Queue接口是Collection接口的子接口,与List接口是平级关系。
该接口主要描述具有先进先出特性的数据结构,简称为FIFO(first in first out),叫队列
该接口的主要实现类是LinkedList类,因为该类在增删方面有一定的优势。

Queue常用的方法

boolean offer(E e) - 将参数指定的元素e插入到当前队列的末尾。

- 若插入成功则返回true,否则返回false。

E poll() - 用于从当前队列的队首移除一个元素并返回。

- 若当前队列为空,则返回null。

E peek() - 用于获取当前队列的队首元素并返回。

- 若当前队列为空,则返回null。

例子:

首先声明Queue类型的引用指向LinkedList类型的对象,分别将数据10 20 30 40 50依次进行入队并打印,然后判断该队列是否为空并打印队首元素值,最后将队列中元素一个一个进行移除并打印。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.LinkedList;
import java.util.Queue;

public class TestQueue {

public static void main(String[] args) {

//使用Queue类型的引用指向LinkedList类的对象
Queue<Integer> q1 = new LinkedList<Integer>();

//实现入队操作
for(int i = 1; i < 6; i++){
boolean b1 = q1.offer(new Integer(i*10));
//System.out.println("b1 = " + b1);
System.out.println(q1);
}

System.out.println("--------------------------");
//判断队列是否为空,以及打印队首元素
System.out.println(q1.isEmpty()? "队列为空": "队列不为空");//队列不为空
System.out.println("队首元素是:" + q1.peek()); //10

System.out.println("--------------------------");
//将队列中的元素一个个进行移除并打印
for(int i = 0; i < 5; i++){
System.out.println("移除的队首元素是:" + q1.poll());
}
}

}