Vector與ArrayList底層實現基本相似,底層都是用數組實現的,最大的不一樣是Vector是線程安全的。ArrayList源碼分析請參考ArrayList源碼分析java
1、源碼分析
基於jdk1.7源碼android
屬性
protected Object[] elementData;//用來存儲元素 protected int elementCount;//元素數量 protected int capacityIncrement;//擴容增量,擴容時增長的容量大小。
Vector多了一個capacityIncrement屬性。當Vector須要擴容時,增長的容量大小就是該值。數組
而ArrayList擴容時是擴充到原容量的1.5倍。安全
構造器
public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } public Vector(int initialCapacity) { this(initialCapacity, 0); } public Vector() { this(10); } 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); }
跟ArrayList同樣,建立Vector時能夠指定初始容量initalCapacity,若是不指定則默認初始容量爲10。源碼分析
Vector也能夠在建立時指定擴容增量,若是不指定則爲0。this
add方法
public synchronized boolean add(E e) { modCount++; //肯定是否還有容量 ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; }
實現與ArrayList差很少,最大區別是該方法進行了同步。繼續往下跟代碼。spa
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同樣,可是不一樣點是Vecotor擴容增長的容量大小。.net
若是Vector初始化時指定了擴容增量,則增長的容量值就是指定的擴容增量,不然,增長1倍容量,也就是擴容到原來的2倍。線程
get方法
public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); }
很簡單,與ArrayList同樣,也是先進行邊界檢查,再根據下標獲取元素。code
remove方法
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; }
跟ArrayList實現差很少,再也不贅述。
2、Vector和ArrayList的比較
1.擴容
Vector在建立時可以指定擴容增量,若是指定了該增量,當自動擴容時增長的容量就是該增量值。若是建立時沒指定增量(或該值<=0),則擴容1倍,即容量變爲原來的2倍。
ArrayList並無提供能指定增量的構造方法,擴容0.5倍,即容量變爲原來的1.5倍(具體參考ArrayList源碼分析)
2.線程安全和效率
Vector的修改方法都是線程安全的,然而java.util.concurrent包中對容器提供了線程安全的實現版本,非線程安全時,能夠用ArrayList來代替Vector,須要線程安全時可使用Collections.synchronizedList(new ArrayList())和CopyOnWriteArrayList來替代,也就是說Vector被淘汰了。
ArrayList並非線程安全的,所以相對來講,ArrayList比Vector效率要高一些。