💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## [队列Queue](https://lingcoder.gitee.io/onjava8/#/book/12-Collections?id=%e9%98%9f%e5%88%97queue) 队列是一个典型的“先进先出”(FIFO)集合。 即从集合的一端放入事物,再从另一端去获取它们,事物放入集合的顺序和被取出的顺序是相同的。队列通常被当做一种可靠的将对象从程序的某个区域传输到另一个区域的途径。队列在[并发编程](https://lingcoder.gitee.io/onjava8/#/)中尤为重要,因为它们可以安全地将对象从一个任务传输到另一个任务。 **LinkedList**实现了**Queue**接口,并且提供了一些方法以支持队列行为,因此**LinkedList**可以用作**Queue**的一种实现。 通过将**LinkedList**向上转换为**Queue**,下面的示例使用了在**Queue**接口中与**Queue**相关(Queue-specific)的方法: ~~~ // collections/QueueDemo.java // Upcasting to a Queue from a LinkedList import java.util.*; public class QueueDemo { public static void printQ(Queue queue) { while(queue.peek() != null) System.out.print(queue.remove() + " "); System.out.println(); } public static void main(String[] args) { Queue<Integer> queue = new LinkedList<>(); Random rand = new Random(47); for(int i = 0; i < 10; i++) queue.offer(rand.nextInt(i + 10)); printQ(queue); Queue<Character> qc = new LinkedList<>(); for(char c : "Brontosaurus".toCharArray()) qc.offer(c); printQ(qc); } } /* Output: 8 1 1 1 5 14 3 1 0 1 B r o n t o s a u r u s */ ~~~ `offer()`是与**Queue**相关的方法之一,它在允许的情况下,在队列的尾部插入一个元素,或者返回**false**。`peek()`和`element()`都返回队头元素而不删除它,但是如果队列为空,则`element()`抛出**NoSuchElementException**,而`peek()`返回**null**。`poll()`和`remove()`\* 都删除并返回队头元素,但如果队列为空,`poll()`返回**null**,而`remove()`抛出**NoSuchElementException**。 自动包装机制会自动将`nextInt()`的**int**结果转换为**queue**所需的**Integer**对象,并将**char c**转换为**qc**所需的**Character**对象。**Queue**接口窄化了对**LinkedList**方法的访问权限,因此只有适当的方法才能使用,因此能够访问到的**LinkedList**的方法会变少(这里实际上可以将**Queue**强制转换回**LinkedList**,但至少我们不鼓励这样做)。 与**Queue**相关的方法提供了完整而独立的功能。 也就是说,对于**Queue**所继承的**Collection**,在不需要使用它的任何方法的情况下,就可以拥有一个可用的**Queue**。