系列文章:
前言
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
三個成員變量:
-
elementData
是Object[]
類型的數組,保存了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 | 棧,先進后出 |