在本教程中,我们将学习 Java Queue接口及其方法。
Java 集合框架的Queue接口提供队列数据结构的功能。 它扩展了Collection接口。
实现Queue的类
由于Queue是一个接口,我们无法提供它的直接实现。
为了使用Queue的功能,我们需要使用实现它的类:

扩展Queue的接口
Queue接口还通过各种子接口扩展:
DequeBlockingQueueBlockingDeque

队列数据结构的工作原理
在队列中,元素以先进先出的方式存储和访问。 即,从后面添加元素,从前面去除元素。

如何使用队列?
在 Java 中,必须导入java.util.Queue包才能使用Queue。
// LinkedList implementation of QueueQueue<String> animal1 = new LinkedList<>();// Array implementation of QueueQueue<String> animal2 = new ArrayDeque<>();// Priority Queue implementation of QueueQueue<String> animal 3 = new PriorityQueue<>();
在这里,我们分别创建了LinkedList,ArrayDeque和PriorityQueue类的对象animal1,animal2和animal3。 这些对象可以使用Queue接口的功能。
Queue方法
Queue接口包含Collection接口的所有方法。 这是因为Collection是Queue的超级接口。
Queue接口的一些常用方法是:
add()- 将指定的元素插入队列。 如果任务成功,则add()返回true,否则将引发异常。offer()- 将指定的元素插入队列。 如果任务成功,则offer()返回true,否则返回false。element()- 返回队列的开头。 如果队列为空,则引发异常。peek()- 返回队列的开头。 如果队列为空,则返回null。remove()- 返回并删除队列的头部。 如果队列为空,则引发异常。poll()- 返回并删除队列的头部。 如果队列为空,则返回null。
Queue接口的实现
1.LinkedList实现类
import java.util.Queue;import java.util.LinkedList;class Main {public static void main(String[] args) {// Creating Queue using the LinkedList classQueue<Integer> numbers = new LinkedList<>();// offer elements to the Queuenumbers.offer(1);numbers.offer(2);numbers.offer(3);System.out.println("Queue: " + numbers);// Access elements of the Queueint accessedNumber = numbers.peek();System.out.println("Accessed Element: " + accessedNumber);// Remove elements from the Queueint removedNumber = numbers.poll();System.out.println("Removed Element: " + removedNumber);System.out.println("Updated Queue: " + numbers);}}
输出
Queue: [1, 2, 3]Accessed Element: 1Removed Element: 1Updated Queue: [2, 3]
要了解更多信息,请访问 Java LinkedList 。
2.PriorityQueue实现类
import java.util.Queue;import java.util.PriorityQueue;class Main {public static void main(String[] args) {// Creating Queue using the PriorityQueue classQueue<Integer> numbers = new PriorityQueue<>();// offer elements to the Queuenumbers.offer(5);numbers.offer(1);numbers.offer(2);System.out.println("Queue: " + numbers);// Access elements of the Queueint accessedNumber = numbers.peek();System.out.println("Accessed Element: " + accessedNumber);// Remove elements from the Queueint removedNumber = numbers.poll();System.out.println("Removed Element: " + removedNumber);System.out.println("Updated Queue: " + numbers);}}
输出:
Queue: [1, 5, 2]Accessed Element: 1Removed Element: 1Updated Queue: [2, 5]
要了解更多信息,请访问 Java PriorityQueue 。
在接下来的教程中,我们将详细了解Queue接口的不同子接口及其实现。
