Java Queue 接口实现
Date: 2025.05.14 20:46:38 author: lijianzhan
Java中的Queue接口是位于java.util包中,它是一个用于表示队列的接口。队列是一种先进先出(First-In-First-Out, 简称为FIFO)的数据结构,其中元素被添加到队列的尾部,并从队列的头部移除。
Queue的方法
Queue接口包括Collection接口的所有方法。 这是因为Collection是Queue的超级接口。
Queue接口的一些常用方法是:
#1. 添加元素
add(element): 将指定的元素插入此队列表示的尾部
offer(element): 插入指定的元素到队列中,如果成功则返回true,如果队列达到其容量则返回false
put(element): throws InterruptedException: 插入指定的元素到队列中,如果队列满,则等待空间变得可用
#2.移除元素
remove(): 获取并移除此队列的头部。如果此队列为空,则抛出异常
poll(): 获取并移除此队列的头部。如果此队列为空,则返回null
#3.检查队列
size(): 返回此队列中的元素数
isEmpty(): 如果此队列不包含元素,则返回true
#4.阻塞队列方法
take(): throws InterruptedException: 获取并移除此队列的头部,在数据不可用时,会等待直到元素可用
实现类
Java提供了几个Queue接口的实现类,包括:
LinkedList: 实现了Queue接口,同时它也实现了List和Deque接口,因此它可以作为队列、栈或双端队列使用。
1.PriorityQueue: 实现了Queue接口,基于优先级堆。此队列按照元素的自然顺序或者构造队列时提供的Comparator进行排序。
2.ArrayBlockingQueue: 实现了BlockingQueue接口,是一个由数组支持的有界队列。
3.LinkedBlockingQueue: 实现了BlockingQueue接口,是一个由链表支持的可选有界队列。
4.PriorityBlockingQueue: 实现了BlockingQueue接口,支持优先级的无界队列。
5.DelayQueue: 实现了BlockingQueue接口,其中元素只有在其指定的延时完成后才能被取出。
6.SynchronousQueue: 实现了BlockingQueue接口,不存储任何元素。每个插入操作必须等待另一个线程的对应移除操作,反之亦然。
7.LinkedTransferQueue: 实现了TransferQueue接口,支持FIFO、可阻塞的put和take以及transfer操作。
队列接口的实现
1.实现LinkedList类,示例代码如下:
import java.util.Queue;
import java.util.LinkedList;public class queue {public static void main(String[] args) {// 创建 Queue 使用LinkedList 类Queue<Integer> queueList = new LinkedList<>();int number = 5;for (int i = 1; i <= number; i++) {//添加元素到 QueuequeueList.offer(i);System.out.println("Queue队列: " + i);}// 访问Queue的元素int accessedNumber = queueList.peek();System.out.println("访问元素: " + accessedNumber);//从队列中Queue元素int removedNumber = queueList.poll();System.out.println("删除元素: " + removedNumber);System.out.println("更新后的 Queue: " + queueList);}
}
运行结果如下:
2.实现PriorityQueue类,示例代码如下:
import java.util.Queue;
import java.util.PriorityQueue;public class queue {public static void main(String[] args) {// 使用PriorityQueue类创建队列Queue<Integer> queueList2 = new PriorityQueue<>();//添加元素到 QueuequeueList2.offer(1);queueList2.offer(2);queueList2.offer(3);System.out.println("Queue: " + queueList2);//访问 Queue 的元素int accessedNumber = queueList2.peek();System.out.println("访问元素: " + accessedNumber);//从 Queue 删除元素int removedNumber = queueList2.poll();System.out.println("删除元素: " + removedNumber);System.out.println("更新后的 Queue: " + queueList2);}
}
运行结果如下:
总结:这两个例子展示了如何使用LinkedList类以及PriorityQueue类来实现一个简单的队列,并演示了如何使用Queue接口的方法来操作这个队列。