隊列是只能在其上執(zhí)行操作的對象的集合兩端的隊列。
隊列有兩個末端,稱為頭和尾。
在簡單隊列中,對象被添加到尾部并從頭部刪除并首先刪除首先添加的對象。
Java Collections Framework支持以下類型的隊列。
簡單隊列由 Queue
接口的實例表示。
隊列允許您執(zhí)行三個基本操作:
Queue接口為三個操作中的每一個定義了兩個方法。如果操作不可能,一個方法拋出異常,另一個方法方法返回false或null以指示失敗。
方法 | 描述 |
---|---|
boolean add(E e) | 如果可能,向隊列中添加一個元素。否則,它拋出異常。 |
boolean offer(E e) | 如果不能添加元素,則將元素添加到隊列中,而不拋出異常。 它在失敗時返回false,在成功時返回true。 |
E remove() | 刪除隊列的頭。如果隊列為空,它會拋出異常。此方法返回已移除的項目。 |
E poll() | 從隊列中刪除元素。如果隊列為空而不是拋出異常,則返回null。 |
Eelement() | 偷看隊列的頭,而不從隊列中刪除它。 如果隊列為空,它會拋出異常。 |
E peek() | 查看隊列,如果隊列為空而不是拋出異常,則返回null。 |
LinkedList和PriorityQueue是Queue接口的兩個實現(xiàn)類。LinkedList還實現(xiàn)了List接口。
以下代碼顯示如何將鏈表用作FIFO隊列。
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é)果。
更多建議: