Java 如何实现大小限制的队列,该队列保存最后N个元素
介绍
队列是Java中的一种接口。它用于在一端插入元素并从另一端移除元素。它使用先进先出(FIFO)原则进行处理。队列扩展了集合框架,并在Java.util接口中定义。
在本教程中,我们将了解在Java中实现大小限制队列的方法。
什么是Java中的大小限制队列
大小限制队列是一个具有固定大小N的队列。它不能容纳超过其大小的元素。如果尝试插入更多的数据,它将从队列的前端删除元素。队列的大小N是固定的。
大小限制队列使用链表类实现,并具有Java中简单队列的所有基本方法。
在Java中实现保存最后N个元素的大小限制队列
我们正在实现一个方法,通过重写队列的add()方法将元素添加到大小限制队列的最后一个大小。
大小限制队列的语法
Queue<data_type> queue_name = new SizeLimitedQueue<>()
代码中使用的方法的语法
- add() = queue_name.add()
-
size() = queue_name.size()
-
peek() = queue_name.peek()
步骤
第一步 : 通过扩展链表类来初始化一个队列
第二步 : 声明一个变量来检查队列的大小。
第三步 : 重写add()方法:当队列达到最大大小时,通过移除前一个元素来添加一个新元素。
第四步 : 打印队列。
示例
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]
解释
在上述代码中:
- 扩展了一个链表类来实现大小为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,队列会移除头元素[3]并存储[4,5,6,7]。
结论
我们在Java中实现了定义大小为N的有限队列的方法。希望这个教程对你有用。