队列是只能在其上执行操作的对象的集合两端的队列。
队列有两个末端,称为头和尾。
在简单队列中,对象被添加到尾部并从头部删除并首先删除首先添加的对象。
Java Collections Framework支持以下类型的队列。
简单队列由 Queue 接口的实例表示。
队列允许您执行三个基本操作:
Queue接口为三个操作中的每一个定义了两个方法。如果操作不可能,一个方法抛出异常,另一个方法方法返回false或null以指示失败。
| 方法 | 描述 |
|---|---|
| boolean add(E e) | 如果可能,向队列中添加一个元素。否则,它抛出异常。 |
| boolean offer(E e) | 如果不能添加元素,则将元素添加到队列中,而不抛出异常。 它在失败时返回false,在成功时返回true。 |
| E remove() | 删除队列的头。如果队列为空,它会抛出异常。此方法返回已移除的项目。 |
| E poll() | 从队列中删除元素。如果队列为空而不是抛出异常,则返回null。 |
| Eelement() | 偷看队列的头,而不从队列中删除它。 如果队列为空,它会抛出异常。 |
| E peek() | 查看队列,如果队列为空而不是抛出异常,则返回null。 |
LinkedList和PriorityQueue是Queue接口的两个实现类。LinkedList还实现了List接口。
以下代码显示如何将链表用作FIFO队列。
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("Java");
// offer() will work the same as add()
queue.offer("SQL");
queue.offer("CSS");
queue.offer("XML");
System.out.println("Queue: " + queue);
// Let"s remove elements until the queue is empty
while (queue.peek() != null) {
System.out.println("Head Element: " + queue.peek());
queue.remove();
System.out.println("Removed one element from Queue");
System.out.println("Queue: " + queue);
}
System.out.println("queue.isEmpty(): " + queue.isEmpty());
System.out.println("queue.peek(): " + queue.peek());
System.out.println("queue.poll(): " + queue.poll());
try {
String str = queue.element();
System.out.println("queue.element(): " + str);
str = queue.remove();
System.out.println("queue.remove(): " + str);
} catch (NoSuchElementException e) {
System.out.println("queue.remove(): Queue is empty.");
}
}
}
上面的代码生成以下结果。

© 著作权归作者所有