Java集合系列05之Vector&Stack源碼分析及List總結

系列文章

前言

Vector是矢量隊列,JDK1.0版本添加的類,是一個動態數組,與ArrayList不同的是Vector支持多線程訪問,是線程安全的,因為內部很多方法都被synchronized關鍵字修飾了,有同步鎖,而且其內部有很多不屬于集合框架的方法。其定義如下:

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

Vector繼承了AbstractList,實現了List,RandomAccess, Cloneable, java.io.Serializable四個接口,支持隨機訪問。

Stack表示先進后出(FILO)的堆棧,是一種常見的數據結構,Stack繼承了Vector,由于Vector是通過數組實現的,因此Stack也是通過數組實現的,而非鏈表。前面介紹LinkedList時,我們也說過可以把LinkedList當作Stack使用。

本文源碼分析基于jdk 1.8.0_121

繼承關系

Vector&Stack繼承關系

java.lang.Object
  |___ java.util.AbstractCollection<E>
      |___ java.util.AbstractList<E>
          |___ java.util.Vector<E>
              |___ java.util.Stack<E>
所有已實現的接口:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

關系圖

Vector&Stack關系圖

Vector的數據結構和ArrayList類似,包含了elementData,elementCount,capacityIncrement三個成員變量:

  • elementDataObject[]類型的數組,保存了Vector的數據,是Vector的底層實現,它是個動態數組,在添加數據過程中不斷擴展容量,初始化時若沒有指定數組大小,則默認的數組大小是10;
  • elementCount是動態數組的實際大小;
  • capacityIncrement是數組容量增長的相關參數,創建Vector時如果指定了capacityIncrement,則Vector每次容量增加時,數組容量增加的大小就是capacityIncrement;創建Vector時沒有指定capacityIncrement,則Vector每次容量增加一倍。

Stack中只定義了一些關于堆棧的操作方法,具體見下文。

構造函數

Vector一共有四個構造函數

// initialCapacity是Vector的默認容量大小
// capacityIncrement是每次數組容量增長的大小
public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

// initialCapacity是Vector的默認容量大小
// 數組容量增加時,每次容量會增加一倍。
public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}

// 默認構造函數,默認容量為10
public Vector() {
    this(10);
}

// 創建包含集合c的數組
public Vector(Collection<? extends E> c) {
    elementData = c.toArray();
    elementCount = elementData.length;
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}

Stack只有一個默認構造函數:

public Stack() {
}

API

Vector API

synchronized boolean        add(E e)
             void           add(int index, E element)
synchronized boolean        addAll(Collection<? extends E> c)
synchronized boolean        addAll(int index, Collection<? extends E> c)
synchronized void           addElement(E obj)
synchronized int            capacity()
             void           clear()
synchronized Object         clone()
             boolean        contains(Object o)
synchronized boolean        containsAll(Collection<?> c)
synchronized void           copyInto(Object[] anArray)
synchronized E              elementAt(int index)
Enumeration<E>              elements()
synchronized void           ensureCapacity(int minimumCapacity)
synchronized boolean        equals(Object o)
synchronized E              firstElement()
             E              get(int index)
synchronized int            hashCode()
synchronized int            indexOf(Object o, int index)
             int            indexOf(Object o)
synchronized void           insertElementAt(E obj, int index)
synchronized boolean        isEmpty()
synchronized E              lastElement()
synchronized int            lastIndexOf(Object o, int index)
synchronized int            lastIndexOf(Object o)
synchronized E              remove(int index)
             boolean        remove(Object o)
synchronized boolean        removeAll(Collection<?> c)
synchronized void           removeAllElements()
synchronized boolean        removeElement(Object obj)
synchronized void           removeElementAt(int index)
synchronized boolean        retainAll(Collection<?> c)
synchronized E              set(int index, E element)
synchronized void           setElementAt(E obj, int index)
synchronized void           setSize(int newSize)
synchronized int            size()
synchronized List<E>        subList(int fromIndex, int toIndex)
synchronized <T> T[]        toArray(T[] a)
synchronized Object[]       toArray()
synchronized String         toString()
synchronized void           trimToSize()

Stack API

       boolean     empty()
synchronized E     peek()
synchronized E     pop()
             E     push(E item)
synchronized int   search(Object o)

源碼分析

Vector源碼分析

成員變量

// 保存Vector數據
protected Object[] elementData;

// 實際數量
protected int elementCount;

// 容量增長數量
protected int capacityIncrement;

// 最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

改變容量值

// 將當前容量值設置為實際元素個數
public synchronized void trimToSize() {
    modCount++;
    int oldCapacity = elementData.length;
    if (elementCount < oldCapacity) {
        elementData = Arrays.copyOf(elementData, elementCount);
    }
}

確定容量

// 確認Vector容量,修改次數+1
public synchronized void ensureCapacity(int minCapacity) {
    if (minCapacity > 0) {
        modCount++;
        ensureCapacityHelper(minCapacity);
    }
}

// 幫助函數,minCapacity大于現在數組實際長度時擴容
private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

// 擴容,capacityIncrement>0 則將容量增大capacityIncrement
// 否則直接將容量擴大一倍
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                     capacityIncrement : oldCapacity);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}

// 當minCapacity超出Integer.MAX_VALUE時,minCapacity變為負數,拋出異常
private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

// 設置容量值為 newSize
public synchronized void setSize(int newSize) {
    modCount++;
    // 如果newSize大于elementCount,則調整容量
    if (newSize > elementCount) {
        ensureCapacityHelper(newSize);
    } else { 
        // 如果newSize小于或等于elementCount,則將newSize位置開始的元素都設置為null
        for (int i = newSize ; i < elementCount ; i++) {
            elementData[i] = null;
        }
    }
    elementCount = newSize;
}

返回Enumeration

// 返回Vector中所有元素對應的Enumeration
public Enumeration<E> elements() {
    return new Enumeration<E>() {
        int count = 0;
        
        // 是否有下一個元素 類似Iterator的hasNext()
        public boolean hasMoreElements() {
            return count < elementCount;
        }
        
        // 獲取下一個元素
        public E nextElement() {
            synchronized (Vector.this) {
                if (count < elementCount) {
                    return elementData(count++);
                }
            }
            throw new NoSuchElementException("Vector Enumeration");
        }
    };
}

增加元素

// 增加元素
public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}

// index處添加元素
public void add(int index, E element) {
    insertElementAt(element, index);
}

// 在index處插入元素
public synchronized void insertElementAt(E obj, int index) {
    modCount++;
    if (index > elementCount) {
        throw new ArrayIndexOutOfBoundsException(index
                                                 + " > " + elementCount);
    }
    ensureCapacityHelper(elementCount + 1);
    System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
    elementData[index] = obj;
    elementCount++;
}

// 添加集合c
public synchronized boolean addAll(Collection<? extends E> c) {
    modCount++;
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityHelper(elementCount + numNew);
    System.arraycopy(a, 0, elementData, elementCount, numNew);
    elementCount += numNew;
    return numNew != 0;
}

// index處開始,將集合c添加到Vector中
public synchronized boolean addAll(int index, Collection<? extends E> c){
    modCount++;
    if (index < 0 || index > elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityHelper(elementCount + numNew);

    int numMoved = elementCount - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                         numMoved);

    System.arraycopy(a, 0, elementData, index, numNew);
    elementCount += numNew;
    return numNew != 0;
}

// 將給定元素添加到Vector中
public synchronized void addElement(E obj) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = obj;
}

刪除元素

// 查找并刪除元素obj
// 查找到則刪除,返回true
// 查找不到則返回false
public synchronized boolean removeElement(Object obj) {
    modCount++;
    int i = indexOf(obj);
    if (i >= 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}

// 刪除index處元素
public synchronized void removeElementAt(int index) {
    modCount++;
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                 elementCount);
    }
    else if (index < 0) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    int j = elementCount - index - 1;
    if (j > 0) {
        System.arraycopy(elementData, index + 1, elementData, index, j);
    }
    elementCount--;
    elementData[elementCount] = null; /* to let gc do its work */
}

// 刪除所有元素
public synchronized void removeAllElements() {
    modCount++;
    // Let gc do its work
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;

    elementCount = 0;
}

// 刪除元素o
public boolean remove(Object o) {
    return removeElement(o);
}

// 刪除index位置處元素,并返回該元素
public synchronized E remove(int index) {
    modCount++;
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);
    E oldValue = elementData(index);

    int numMoved = elementCount - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--elementCount] = null; // Let gc do its work

    return oldValue;
}

設置元素

// 設置index處元素為element,并返回index處原來的值
public synchronized E set(int index, E element) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

// 設置index處元素為obj
public synchronized void setElementAt(E obj, int index) {
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                 elementCount);
    }
    elementData[index] = obj;
}

獲取元素

// 獲取index處元素
public synchronized E get(int index) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    return elementData(index);
}

Stack源碼分析

package java.util;

public class Stack<E> extends Vector<E> {
   
    // 構造函數
    public Stack() {
    }

    // 棧頂元素入頂
    public E push(E item) {
        // addElement的實現在Vector.java中
        addElement(item);
        return item;
    }

    // 刪除棧頂元素
    public synchronized E pop() {
        E obj;
        int len = size();
        obj = peek();
        // removeElementAt的實現在Vector.java中
        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;
    }

    // 查找元素o在棧中位置,由棧底向棧頂方向
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);
        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

    // 版本ID
    private static final long serialVersionUID = 1224463164541339165L;
}

Stack的源碼比較簡單,內部也是通過數組實現的,執行push時將元素追加到數組末尾,執行peek時返回數組末尾元素(不刪除該元素),執行pop時取出數組末尾元素,并將該元素從數組中刪除。

Vector遍歷方式

  • 迭代器遍歷
Iterator iter = vector.iterator();
while(iter.hasNext()) {
    iter.next();
}
  • 隨機訪問
for (int i=0; i<vector.size(); i++) {
    vector.get(i);        
}
  • foreach循環
for (Integer integ:vector) {
    ;
}
  • Enumeration遍歷
Enumeration enu = vector.elements();
while(enu.hasMoreElements()) {
    enu.nextElement();
}

以上各種方式中,隨機訪問效率最高。

List總結

概述

下面是List的關系圖:

List

上圖總結如下:

  • List是接口,繼承Collection,是一個有序隊列
  • AbstractList是抽象類,繼承了AbstractCollection類,并實現了List接口,提供了 List 接口的大部分實現
  • AbstractSequentialList 繼承自 AbstractList,是 LinkedList 的父類,提供了List接口大部分實現。 AbstractSequentialList 實現了鏈表中的“隨機訪問”方法
  • ArrayList,LinkedList,Vector,Stack是四個隊列集合,List的四個實現類

比較

隊列集合 特點 使用場景 訪問效率
ArrayList 數組隊列,動態增長,非線程安全 快速隨機訪問場景下,單線程 隨機訪問效率高,隨機插入、隨機刪除效率低
LinkedList 雙向鏈表,可當做隊列,堆棧,雙端隊列 快速插入,刪除場景下,單線程 隨機訪問效率低,隨機插入、隨機刪除效率低
Vector 向量隊列,動態增長,線程安全 多線程場景下
Stack 棧,先進后出

參考內容

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,321評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,559評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,442評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,835評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,581評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,922評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,931評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,096評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,639評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,374評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,591評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,104評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,789評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,196評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,524評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,322評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,554評論 2 379

推薦閱讀更多精彩內容