如何在Java中实现大小受限的队列,以保存最后N个元素?
介绍
队列是Java中的一个接口。它用于在一个端插入元素,并在另一个端移除元素。它使用FIFO原则进行处理。队列扩展了集合框架,并在Java.util接口中定义。
在本教程中,我们将了解在Java中实现大小受限队列的方法。
什么是Java中的大小受限队列?
大小受限队列是一个大小为N的固定大小的队列。它不能容纳超过其大小的元素。如果尝试推送更多数据,它将从前端移除元素。队列的大小固定为N。
大小受限队列使用LinkedList类实现,并具有Java中简单队列的所有基本方法。
在Java中实现保存最后N个元素的大小受限队列
我们正在实现一个方法,通过覆盖队列的add()方法,将元素添加到大小受限队列,直到队列的最后大小。
大小受限队列的语法
Queue<data_type> queue_name = new SizeLimitedQueue<>()
代码中使用的方法语法
add()= queue_name.add()
size()= queue_name.size()
peek()= queue_name.peek()
算法
步骤1:通过扩展LinkedList类初始化队列
步骤2:声明一个变量来检查队列的大小。
步骤3:重写add()方法:当队列达到其最大大小时,通过移除前端元素来添加新元素。
步骤4:打印队列。
示例
import java.util.LinkedList;
import java.util.Queue;
public class SVQ {
//size limited queue extends the Linked List class
public static class SizeLimitedQueue<E> extends LinkedList<E> {
//declaring a variable of size limited queue to check the queue size
private int QueueVariable;
//initializing the constructor method
public SizeLimitedQueue(int QueueVariable) {
this.QueueVariable = QueueVariable;
}
//overriding the add() method of Queue, so that Queue adds elements to the QueueVariable else remove the front element and add a new element.
@Override
public boolean add(E o) {
//remove front element, if Queue reached its maximum size
while (this.size() == QueueVariable) {
super.remove();
}
super.add(o);
return true;
}
}
public static void main(String[] args) {
//initializing a Size limited queue of size 4
Queue<Integer> sq = new SizeLimitedQueue<>(4);
//adding elements {0, 1, 2, 3, 4, 5} to the queue
for (int x = 0; x < 6; x++)
sq.add(x);
//Printing size of the Queue
int size = sq.size();
System.out.println("Size of queue-" + size);
//Printing Queue elements and Queue has {2, 3, 4, 5} and {0, 1} are removed due to size of the queue
System.out.println("Elements of queue " + sq);
//removing queue front element
int h = sq.remove();
System.out.println("Removed element-" + h);
System.out.println("Elements of queue " + sq);
// print head of the Queue
int hq = sq.peek();
System.out.println("Head of queue-" + hq);
//adding 6,7 to the queue
for (int x = 6; x < 8; x++)
sq.add(x);
System.out.println("Elements of queue " + sq);
}
}
输出
Size of queue-4 Elements of Queue [2, 3, 4, 5] Removed element-2 Elements of queue [3, 4, 5] Head of queue-3 Element of queue [4, 5, 6, 7]
解释
在上面的代码中:
扩展LinkedList类以实现大小为4的大小受限队列pq。
定义一个变量QueueVariable来控制已定义队列的大小。
重写add方法,以便一次仅向队列pq添加4个元素。如果添加新元素,队列将移除前端元素。
向队列中添加0、1、2、3、4、5。pq将只存储4个元素,同时移除前端元素。生成的队列元素为[2, 3, 4, 5]。
从队列中移除前端元素2。现在,队列(pq)只有3个元素[3, 4, 5],它还有一个新的数据空间。
再次向队列添加元素6和7。
队列pq只有一个空间,因此为了添加6和7,pq将移除头部元素[3]并存储[4, 5, 6, 7]
结论
我们实现了一种方法来在Java中定义大小为N的大小受限队列。我希望本教程对您有所帮助。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP