java Stack
-
stack是一個後進先出的資料結構,繼承於vector,自身提供了五種方法,pop、push、empty、peek、search
-
本文主要介紹
-
pop 將一個元素入棧
-
push 將一個元素出棧
-
package java.util;
/**
* The {@code Stack} class represents a last-in-first-out
* (LIFO) stack of objects. It extends class {@code Vector} with five
* operations that allow a vector to be treated as a stack. The usual
* {@code push} and {@code pop} operations are provided, as well as a
* method to {@code peek} at the top item on the stack, a method to test
* for whether the stack is {@code empty}, and a method to {@code search}
* the stack for an item and discover how far it is from the top.
// stack是一個後進先出的棧物件,繼承了vector,有5個方法
// 1.push 2.pop 3.peek 4.empty 5.search
* <p>
* When a stack is first created, it contains no items.
*
* <p>A more complete and consistent set of LIFO stack operations is
* provided by the {@link Deque} interface and its implementations, which
* should be used in preference to this class. For example:
* <pre> {@code
// 這個是說使用deque來實現更好,deque提供了更多的方法
* Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
*
* @author Jonathan Payne
* @since 1.0
*/
public class Stack<E> extends Vector<E> {
/**
* 建立了一個新的stack
*/
public Stack() {
}
/**
往棧中加入一個元素
*/
public E push(E item) {
addElement(item);
return item;
}
================================addElement============================================
public synchronized void addElement(E obj) {
modCount++;
add(obj, elementData, elementCount);
}
================================add============================================
private void add(E e, Object[] elementData, int s) {
//如果陣列已滿就使用grow() 方法進行擴容
if (s == elementData.length)
elementData = grow();
//直接賦值
elementData[s] = e;
//在讓元素個數加一
elementCount = s + 1;
}
/**
移除一個最後的元素並且返回該元素的值。
*/
public synchronized E pop() {
E obj;
//獲得陣列的當前長度
int len = size();
//獲得陣列的最後一個數值
obj = peek();
//移除位於陣列最後的元素
removeElementAt(len - 1);
return obj;
}
/******************************************removeElementAt**************************************/
//移除最後一個元素的邏輯
public synchronized void removeElementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
//計算index位置後需要移動的個數,這個比較好,直接提高了方法的複用性
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
//記錄修改次數
modCount++;
//元素個數減一
elementCount--;
//將該位置設定為null,便於jvm進行垃圾回收
elementData[elementCount] = null; /* to let gc do its work */
}
/**
* Looks at the object at the top of this stack without removing it
* from the stack.
*
* @return the object at the top of this stack (the last item
* of the {@code Vector} object).
*/
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
}