1. 程式人生 > >Java佇列詳解之 LinkedList 類

Java佇列詳解之 LinkedList 類

Java佇列詳解之 LinkedList

1. 類簡介

  • 類釋義

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.

用於在處理前儲存元素而設計的 Collection【說明這個是繼承自 Collection 介面】

  • 繼承關係
    在這裡插入圖片描述

2. 類方法

2.1 add 方法

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

2.1 peek

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

2.1 poll

Retrieves and removes the head of this queue, or returns null if this queue is empty.

3. 簡單示例

 public Queue<String> getFreeIpInQueue(WebSite webSite) {
Queue<String> queue = new LinkedList <String>(); queue.add("a"); queue.add("b"); System.out.println(queue.size()); for (String s : queue) { System.out.println("The content is: "+s); } //peek: Retrieves, but does not remove, the head of this queue or returns null if this queue is empty. System.out.println("peek of queue is: "+queue.peek()); System.out.println("after peek() "+queue.size()); //Retrieves and removes the head of this queue, or returns null if this queue is empty. System.out.println(""+queue.poll()); System.out.println("after poll() "+queue.size()); return queue; }

執行結果如下:
在這裡插入圖片描述