List類是以物件加入(add)容器的順序來排列它們,如果您的物件加入之後大都是為了取出,而不會常作移除或插入(Insert)的動作,則使用ArrayList,如果您會經常從容器中作移除或插入物件的動作,則使用LinkedList會獲得較好的效能。
LinkedList實作了List介面,並增加了一些移除與插入物件的特定方法,像是addFirst()、addLast()、 getFirst()、getLast()、removeFirst( )、removeLast()等等,由於在插入與移除時有較好的效能,適合拿來實作堆疊(Stack)與佇列(Queue)。
以下實作一個簡單的FILO(First-In, Last-Out)堆疊,可以存入字串:
package onlyfun.caterpillar; import java.util.*; public class StringStack { private LinkedList<String> linkedList; public StringStack() { linkedList = new LinkedList<String>(); } public void push(String name) { linkedList.addFirst(name); } public String top() { return linkedList.getFirst(); } public String pop() { return linkedList.removeFirst(); } public boolean isEmpty() { return linkedList.isEmpty(); } }
而對於FIFO(First-In, First-Out)的佇列,我們也可以使用LinkedList來實作:
package onlyfun.caterpillar; import java.util.*; public class StringQueue { private LinkedList<String> linkedList; public StringQueue() { linkedList = new LinkedList<String>(); } public void put(String name) { linkedList.addFirst(name); } public String get() { return linkedList.removeLast(); } public boolean isEmpty() { return linkedList.isEmpty(); } }
事實上,如果您要使用佇列的功能,您也不用親自實作,在J2SE
5.0中,LinkedList也實作了新加入的java.util.Queue介面,這個介面有五個必須實作的方法:
element() |
取得但不移除佇列第一個元件,佇列為空時會丟出例外 |
offer() |
加入一個元素至佇列中 |
peek() |
取得但不移除佇列第一個元件 |
poll() |
取得並移去佇列第一個元件,佇列為空時傳回null |
remove() |
取得並移除佇列第一個元件 |
要使用佇列的功能,您只要類似這樣的宣告:
Queue<String> queue = new LinkedList<String>();
|