棧:
public class Stack<E> extends Vector<E> { // 使用數組實現棧 // 構造一個空棧 public Stack() { } // 壓入棧頂部 public E push(E item) { addElement(item); return item; } // 移除棧頂的對象,並返回 public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; } // 查看棧頂的對象,但不從棧中移除它 public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } // 判斷棧是否為空 public boolean empty() { return size() == 0; } //返回對象在棧中的位置,以 1 為基數。 public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; } }
隊列接口:
FIFO (first-in-first-out)
package java.util; /** * @see java.util.Collection * @see LinkedList * @see PriorityQueue * @see java.util.concurrent.LinkedBlockingQueue * @see java.util.concurrent.BlockingQueue * @see java.util.concurrent.ArrayBlockingQueue * @see java.util.concurrent.LinkedBlockingQueue * @see java.util.concurrent.PriorityBlockingQueue * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public interface Queue<E> extends Collection<E> { // 添加一個元素,如果隊列已滿則拋出IllegalStateException 異常 boolean add(E e); // 添加一個元素返回是否成功 boolean offer(E e);
// 移除並返回隊首的元素,如果隊列為空,拋出NoSuchElementException E remove(); // 移除並返回隊首元素,如果隊列為空,返回null E poll(); // 返回隊列頭部的元素,並不移除,如果隊列為空,拋出NoSuchElementException E element();
// 返回隊列頭部的元素,並不移除,如果隊列為空,返回null E peek(); }
LinkedBlockingQueue:待續