HOWTO · Java
Java 中的 FIFO 佇列
本文介紹了 Java 中的 FIFO 和佇列。
佇列是實現先進先出概念的線性資料結構。這個概念意味著先進入的元素最先出來。
代表佇列的技術術語使用前端和後端。元素從後端新增到 Queue 並從前端取出。
這個概念的真例項子是售票櫃檯排,站在第一個位置的人最先拿到票。現在在 Java 中,概念或資料結構在 Queue 介面中實現。該介面存在於 java.util 包中。
下面是演示佇列結構的程式碼塊。
package F10;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue queue = new LinkedList<String>();
queue.add("First");
queue.add("Second");
queue.add("third");
System.out.println("Created Queue: " + queue);
String value = (String) queue.remove();
System.out.println("The element deleted from the head is: " + value);
System.out.println("The queue after deletion: " + queue);
String head = (String) queue.peek();
System.out.println("The head of the present queue is: " + head);
int size = queue.size();
System.out.println("The size of the queue is: " + size);
}
}
有多種方法可以在 Java 中實現 Queue 資料結構。在上面的程式碼塊中,LinkedList 的使用實現了這個概念。
首先,使用 new LinkedList 語句例項化 Queue 引用。add 方法存在於 Queue 介面中,它將指定的元素插入到 Queue 中。附加值時,該函式返回布林值 true。
當由於大小限制而無法新增元素時,該方法可能會丟擲 IllegalStateException。當傳遞的值為空時,它也會丟擲 NullPointerException。當初始元素集被附加到列表中時,佇列就會被列印出來。System.out.println 語句採用需要列印的字串。
接下來,在 Queue 例項上呼叫 remove 函式。它將刪除存在於佇列頭部的元素,因此返回頭部元素。
有一個類似的 poll 函式也可以刪除頭部的元素。唯一的區別在於 remove 函式在 Queue 為空時丟擲 NoSuchElementException。刪除的值儲存在變數中並列印。列印剩餘的佇列以檢查剩餘的元素。
peek 函式檢索佇列中最頂層的元素並且不會刪除它;它是一種檢查佇列頭部元素的方法。當佇列為空時,該函式返回頭部值並丟擲 NoSuchElementException。size 函式存在於 Collection 介面中,並返回集合的大小。因此,此方法列印佇列中剩餘元素的大小。
輸出:
Created Queue: [First, Second, third]
The element deleted from the head is: First
The Queue after deletion: [Second, third]
The head of the present Queue is: Second
The size of the Queue is: 2