如何在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