隊(duì)列是只能在其上執(zhí)行操作的對(duì)象的集合兩端的隊(duì)列。
隊(duì)列有兩個(gè)末端,稱為頭和尾。
在簡(jiǎn)單隊(duì)列中,對(duì)象被添加到尾部并從頭部刪除并首先刪除首先添加的對(duì)象。
Java Collections Framework支持以下類型的隊(duì)列。
簡(jiǎn)單隊(duì)列由 Queue
接口的實(shí)例表示。
隊(duì)列允許您執(zhí)行三個(gè)基本操作:
Queue接口為三個(gè)操作中的每一個(gè)定義了兩個(gè)方法。如果操作不可能,一個(gè)方法拋出異常,另一個(gè)方法方法返回false或null以指示失敗。
方法 | 描述 |
---|---|
boolean add(E e) | 如果可能,向隊(duì)列中添加一個(gè)元素。否則,它拋出異常。 |
boolean offer(E e) | 如果不能添加元素,則將元素添加到隊(duì)列中,而不拋出異常。 它在失敗時(shí)返回false,在成功時(shí)返回true。 |
E remove() | 刪除隊(duì)列的頭。如果隊(duì)列為空,它會(huì)拋出異常。此方法返回已移除的項(xiàng)目。 |
E poll() | 從隊(duì)列中刪除元素。如果隊(duì)列為空而不是拋出異常,則返回null。 |
Eelement() | 偷看隊(duì)列的頭,而不從隊(duì)列中刪除它。 如果隊(duì)列為空,它會(huì)拋出異常。 |
E peek() | 查看隊(duì)列,如果隊(duì)列為空而不是拋出異常,則返回null。 |
LinkedList和PriorityQueue是Queue接口的兩個(gè)實(shí)現(xiàn)類。LinkedList還實(shí)現(xiàn)了List接口。
以下代碼顯示如何將鏈表用作FIFO隊(duì)列。
import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; public class Main { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); queue.add("Java"); // offer() will work the same as add() queue.offer("SQL"); queue.offer("CSS"); queue.offer("XML"); System.out.println("Queue: " + queue); // Let"s remove elements until the queue is empty while (queue.peek() != null) { System.out.println("Head Element: " + queue.peek()); queue.remove(); System.out.println("Removed one element from Queue"); System.out.println("Queue: " + queue); } System.out.println("queue.isEmpty(): " + queue.isEmpty()); System.out.println("queue.peek(): " + queue.peek()); System.out.println("queue.poll(): " + queue.poll()); try { String str = queue.element(); System.out.println("queue.element(): " + str); str = queue.remove(); System.out.println("queue.remove(): " + str); } catch (NoSuchElementException e) { System.out.println("queue.remove(): Queue is empty."); } } }
上面的代碼生成以下結(jié)果。
更多建議: