1. 程式人生 > >資料結構(三)Stack和Vector原始碼分析

資料結構(三)Stack和Vector原始碼分析

一、基本概念:

1、棧是什麼?
是一個只能在某一端進行插入、刪除操作的線性表。
* 從棧頂插入一個元素稱之為入棧(push)
* 從棧頂刪除一個元素稱之為出棧(pop)

2、圖解:
這裡寫圖片描述
3、棧的實現:

  • 鏈式儲存(連結串列)
  • 順序儲存(陣列)

4、繼承關係:

public class Stack<E> extends Vector<E> {
...
}

二、常用方法:

1、入棧

public E push(E item) {
    //呼叫Vector方法
    addElement(item);
    return
item; }

2、出棧(返回棧頂元素,並刪除)

public synchronized E pop() {
    E obj;
    int len = size();
    //通過呼叫peek獲取棧頂元素
    obj = peek();
    //呼叫Vector的removeElementAt方法
    removeElementAt(len - 1);
    return obj;
}

3、獲取棧頂元素(不刪除)

public synchronized E peek() {
    int len = size();
    if (len == 0)
        throw
new EmptyStackException(); //Vector方法 return elementAt(len - 1); }

4、查詢某元素位置

public synchronized int search(Object o) {
    //Vector方法
    int i = lastIndexOf(o);
    if (i >= 0) {
        return size() - i;
    }
    return -1;
}

三、Vector原始碼分析

1、變數

public class Vector<E>
    extends
AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
//內部實現為陣列 protected Object[] elementData; ... }

2、新增元素

public synchronized void addElement(E obj) {
    modCount++;
    //擴容
    ensureCapacityHelper(elementCount + 1);
    //在陣列最後賦值
    elementData[elementCount++] = obj;
}

Stack入棧的操作就是在陣列的尾部插入元素

3、刪除陣列尾部元素:

public synchronized void removeElementAt(int index) {
    modCount++;
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                 elementCount);
    }
    else if (index < 0) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    //index = elementCount-1,此時為出棧(移除陣列尾部元素)
    int j = elementCount - index - 1;
    if (j > 0) {
        System.arraycopy(elementData, index + 1, elementData, index, j);
    }
    elementCount--;
    //尾部賦值為null
    elementData[elementCount] = null; /* to let gc do its work */
}

Stack出棧的操作就是將陣列尾部的元素移除

4、獲取某位置元素:

public synchronized E elementAt(int index) {
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
    }
    return elementData(index);
}
//獲取陣列某索引元素
E elementData(int index) {
    return (E) elementData[index];
}

5、獲取某元素所在的位置:

public synchronized int lastIndexOf(Object o) {
    return lastIndexOf(o, elementCount-1);
}

public synchronized int lastIndexOf(Object o, int index) {
    if (index >= elementCount)
        throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
    if (o == null) {
        for (int i = index; i >= 0; i--)
            if (elementData[i]==null)
                return i;
    } else {
        //遍歷陣列獲取到元素的位置
        for (int i = index; i >= 0; i--)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

6、結論:

Vector特點:

  • 內部實現為陣列
  • 方法通過synchronized修飾,執行緒安全

Stack特點:

  • 入棧出棧的操作,本質就是對陣列尾部新增、刪除元素。