集合系列 List:Vector

Vector 的底層實現以及結構與 ArrayList 完全相同,只是在某一些細節上會有所不同。這些細節主要有:

  • 線程安全
  • 擴容大小
  • 線程安全

我們知道 ArrayList 是線程不安全的,只能在單線程環境下使用。而 Vector 則是線程安全的,那麼其實怎麼實現的呢?

其實 Vector 的實現很簡單,就是在每一個可能發生線程安全的方法加上 synchronized 關鍵字。這樣就使得任何時候只有一個線程能夠進行讀寫,這樣就保證了線程安全。

public synchronized E get(int index) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    return elementData(index);
}
public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}

擴容大小

與 ArrayList 類似,Vector 在插入元素時也會檢查容量並擴容。在 Vector 中這個方法是:ensureCapacityHelper。

private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
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);
}

其實上述擴容的思路與 ArrayList 是相同,唯一的區別是 Vector 的擴容大小。

int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                     capacityIncrement : oldCapacity);

從上面的代碼可以看到:如果 capacityIncrement 大於 0,那麼就按照 capacityIncrement 去擴容,否則擴大爲原來的 2倍。而 ArrayList 則是擴大爲原來的 1.5 倍。

總結

Vector 與 ArrayList 在實現方式上是完全一致的,但是它們在某些方法有些許不同:

第一,Vector 是線程安全的,而 ArrayList 是線程不安全的。Vector 直接使用 synchronize 關鍵字實現同步。
第二,Vector 默認擴容爲原來的 2 被,而 ArrayList 默認擴容爲原來的 1.5 倍。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章