java集合(二)List集合之Vector詳解


簡介
Vector的內部實現類似於ArrayList,Vector也是基於一個容量能夠動態增長的數組來實現的,該類是JDK1.0版本添加的類,它的很多實現方法都加入了同步語句,因此是線程安全的(但Vector其實也只是相對安全,有些時候還是要加入同步語句來保證線程的安全,我們后面會有例子來說明這一點)。

Vector類聲明如下

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

Vector繼承於AbstractList,實現了List、RandomAccess、Cloneable、 Serializable等接口。

ArrayList實現了List接口,可以對它進行隊列操作;實現了RandmoAccess接口,即提供了隨機訪問功能;實現了Cloneable接口,能被克隆;實現了Serializable接口,因此它支持序列化,能夠通過序列化傳輸。

Vector源碼詳解
Vector內部通過一個Object數組來存儲數據:

protected Object[] elementData;

Vector使用elementCount變量來表示實際存儲的元素個數:

protected int elementCount;

Vector有四個構造方法:

// 創建一個空的Vector,並且指定了Vector的初始容量和擴容時的增長系數
public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                            initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}
 
// 創建一個空的Vector,並且指定了Vector的初始容量
public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}
 
// 創建一個空的Vector,並且指定了Vector的初始容量為10
public Vector() {
    this(10);
}
 
// 根據其他集合來創建一個非空的Vector
public Vector(Collection<? extends E> c) {
    elementData = c.toArray();
    elementCount = elementData.length;
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}

我們下面主要來看一看Vector的add和remove方法

add方法

Vector有兩個重載的Add方法:

// 在數組elementData尾部添加一個元素
public synchronized boolean add(E e)
// 在數組elementData指定位置index處添加元素
public void add(int index, E element)
add(E e)方法

add(E e)方法源碼如下:

// 在數組elementData尾部添加一個元素
public synchronized boolean add(E e) {
    modCount++;
    // 容量大小判斷
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}

該方法首先要判斷elementData數組的容量是否能夠容納新的元素,若不能,則需要進行擴容操作,然后將元素e放置在數組的size位置。ensureCapacityHelper(int)方法源碼如下:

private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    // 增加元素后,ArrayList中要存儲的元素個數為minCapacity
    // 若此時minCapacity > elementData原始的容量,則要按照minCapacity進行擴容
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

擴容的最終操作是通過grow(int)方法來實現的:

private void grow(int minCapacity) {
    // overflow-conscious code
    // 獲取elementData的原始容量
    int oldCapacity = elementData.length;
    // 計算新的容量
    // 如果在構造方法中設置了capacityIncrement > 0,那么新數組長度就是原數組長度 + capacityIncrement
    // 否則,新數組長度就是原數組長度 * 2
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                        capacityIncrement : oldCapacity);
    // 若進行擴容后,capacity仍然比實際需要的小,則新容量更改為實際需要的大小,即minCapacity
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    // 如果新數組的長度比虛擬機能夠提供給數組的最大存儲空間大,則將新數組長度更改為最大正數:Integer.MAX_VALUE
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // 按照新的容量newCapacity創建一個新數組,然后再將原數組中的內容copy到新數組中
    elementData = Arrays.copyOf(elementData, newCapacity);
}

和ArrayList的擴容步驟很相似,這里不再介紹。

add(int index, E element)方法

add(int index, E element)方法源碼如下:

public void add(int index, E element) {
    insertElementAt(element, index);
}

該方式其實是調用了insertElementAt方法:

public synchronized void insertElementAt(E obj, int index) {
    // fail-fast機制
    modCount++;
    // 判斷index下標的合法性
    if (index > elementCount) {
        throw new ArrayIndexOutOfBoundsException(index
                                                    + " > " + elementCount);
    }
    // 判斷容量大小
    ensureCapacityHelper(elementCount + 1);
    // 數組拷貝,將index到末尾的元素拷貝到index + 1到末尾的位置,將index的位置留出來
    System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
    elementData[index] = obj;
    elementCount++;
}

remove方法

remove方法在Vector中同樣有兩種實現方式:

// 根據元素刪除
public boolean remove(Object o)
// 根據index下標刪除元素
public synchronized E remove(int index)

我們先看remove(Object o)方法。

remove(Object o)方法

remove(Object o)方法源碼如下:

public boolean remove(Object o) {
    return removeElement(o);
}

其內部通過removeElement方法來刪除元素:

public synchronized boolean removeElement(Object obj) {
    // fail-fast機制
    modCount++;
    // 查找元素obj在數組中的下標
    int i = indexOf(obj);
    // 若下標 >= 0
    if (i >= 0) {
        // 調用removeElementAt(int)方法刪除元素
        removeElementAt(i);
        return true;
    }
    return false;
}

我們先來看indexOf(Object)方法:

public int indexOf(Object o) {
    return indexOf(o, 0);
}
public synchronized int indexOf(Object o, int index) {
    // 若要查找的元素為null
    if (o == null) {
        for (int i = index ; i < elementCount ; i++)
            if (elementData[i]==null)
                return i;
    } 
    // 若要查找的元素不為null
    else {
        for (int i = index ; i < elementCount ; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

Vector查找元素時,是分為元素為null和不為null兩種方式來判斷的,這也說明Vector允許添加null元素;同時,如果這個元素在Vector中存在多個,則只會找出從index開始,最先出現的那個。

找到元素對應的下標,若下標 >= 0,則說明元素在數組中存在,然后通過removeElementAt(int)方法來刪除元素,removeElementAt(int)方法源碼如下:

public synchronized void removeElementAt(int index) {
    modCount++;
    // index下標合法性檢驗
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                    elementCount);
    }
    else if (index < 0) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    // 要移動的元素個數
    int j = elementCount - index - 1;
    if (j > 0) {
        // 將index之后的元素向前移動一位
        System.arraycopy(elementData, index + 1, elementData, index, j);
    }
    elementCount--;
    elementData[elementCount] = null; /* to let gc do its work */
}
remove(int index)方法

remove(int index)方法源碼如下:

public synchronized E remove(int index) {
    modCount++;
    // index下標合法性檢驗
    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;
}

Vector的相對線程安全

我們前面說過Vector是相對線程安全的,為什么這么說呢?

我們看下面一段代碼:

public class VectorTest {
    static class MyThread extends Thread {
        private CountDownLatch countDownLatch;
        private Vector<String> vector;
        private String element;
        
        public MyThread(CountDownLatch countDownLatch, Vector<String> vector, String element) {
            this.countDownLatch = countDownLatch;
            this.vector = vector;
            this.element = element;
        }
        
        @Override
        public void run() {
            super.run();
            
            try {
                if (!vector.contains(element)) {
                    // 注意這里
                    Thread.sleep(1000);
                    vector.add(element);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Vector<String> vector = new Vector<>();
        
        MyThread myThread1 = new MyThread(countDownLatch, vector, "abc");
        MyThread myThread2 = new MyThread(countDownLatch, vector, "abc");
        
        myThread1.start();
        myThread2.start();
        
        countDownLatch.await();
        
        int vectorSize = vector.size();
        System.out.println("vector size: " + vectorSize);
        for (int i = 0; i < vectorSize; i++) {
            System.out.println("index " + i + ": " + vector.get(i));
        }
    }
}

運行結果(不唯一):

vector size: 2
index 0: abc
index 1: abc

注意注釋處的一段代碼,該段代碼是判斷元素element是否存在,不存在的話,則將其添加到vector之中,如果線程1和線程2同時運行該段代碼,設想一下如下情景:

線程1通過vector.contains(element)同步方法來判斷元素是否存在,此時,該方法返回false,即表明線程1可以將element元素插入Vector中;但是運行完該方法之后,線程1開始sleep,那這時,線程2開始運行vector.contains(element)同步方法,該方法仍然返回了false,即線程2可以將element元素插入Vector中,然后線程2開始sleep,最終結果,就是線程1和線程2都將元素“abc”添加到了vector之中,這就是我們為什么說Vector是相對線程安全的了。

要解決該問題,需要我們在自己的業務代碼代碼中進行同步控制,比如將那一段代碼修改為如下:

synchronized (vector) {
    if (!vector.contains(element)) {
        Thread.sleep(1000);
        vector.add(element);
    }
}

則程序運行結果為:

vector size: 1
index 0: abc

可以看到,這才是我們預期的結果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM