1. Vector的簡介 JDK1.7.0_79版本
Vector 類可以實現可增長的對象數組。與數組一樣,它包含可以使用整數索引進行訪問的組件。但是,Vector 的大小可以根據需要增大或縮小,以適應創建 Vector 后進行添加或移除項的操作。Vector 是同步的,可用於多線程。
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
-
Vector 繼承了AbstractList,實現了List;所以,它是一個隊列,支持相關的添加、刪除、修改、遍歷等功能。
-
Vector實現了RandmoAccess接口,即提供了隨機訪問功能。RandmoAccess是java中用來被List實現,為List提供快速訪問功能的。在Vector中,我們即可以通過元素的序號快速獲取元素對象;這就是快速隨機訪問。
-
Vector 實現了Cloneable接口,即實現clone()函數。它能被克隆。
-
Vector 實現Serializable接口,支持序列化。
2.Vector的繼承關系
java.lang.Object
繼承者 java.util.AbstractCollection<E>
繼承者 java.util.AbstractList<E>
繼承者 java.util.Vector<E>
所有已實現的接口:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
直接已知子類:
Stack
3.Vector的API
注意方法有synchronized 修飾的,實現同步!
synchronized boolean add(E object)
void add(int location, E object)
synchronized boolean addAll(Collection<? extends E> collection)
synchronized boolean addAll(int location, Collection<? extends E> collection)
synchronized void addElement(E object)
synchronized int capacity()
void clear()
synchronized Object clone()
boolean contains(Object object)
synchronized boolean containsAll(Collection<?> collection)
synchronized void copyInto(Object[] elements)
synchronized E elementAt(int location)
Enumeration<E> elements()
synchronized void ensureCapacity(int minimumCapacity)
synchronized boolean equals(Object object)
synchronized E firstElement()
E get(int location)
synchronized int hashCode()
synchronized int indexOf(Object object, int location)
int indexOf(Object object)
synchronized void insertElementAt(E object, int location)
synchronized boolean isEmpty()
synchronized E lastElement()
synchronized int lastIndexOf(Object object, int location)
synchronized int lastIndexOf(Object object)
synchronized E remove(int location)
boolean remove(Object object)
synchronized boolean removeAll(Collection<?> collection)
synchronized void removeAllElements()
synchronized boolean removeElement(Object object)
synchronized void removeElementAt(int location)
synchronized boolean retainAll(Collection<?> collection)
synchronized E set(int location, E object)
synchronized void setElementAt(E object, int location)
synchronized void setSize(int length)
synchronized int size()
synchronized List<E> subList(int start, int end)
synchronized <T> T[] toArray(T[] contents)
synchronized Object[] toArray()
synchronized String toString()
synchronized void trimToSize()
4.Vector源碼分析
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* 存儲向量組件的數組緩沖區。
*/
protected Object[] elementData;
/**
* Vector 對象中的有效組件數。
*/
protected int elementCount;
/**
* 向量的大小大於其容量時,容量自動增加的量。
* 即 容量增長系數
* @serial
*/
protected int capacityIncrement;
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -2767605614048989439L;
/**
* Constructs an empty vector with the specified initial capacity and
* capacity increment.
*
* 使用指定的初始容量和容量增量構造一個空的向量。
* 指定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;
}
/**
* Constructs an empty vector with the specified initial capacity and
* with its capacity increment equal to zero.
*
* 使用指定的初始容量和等於零的容量增量構造一個空向量。
*/
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
/**
* Constructs an empty vector so that its internal data array
* has size {@code 10} and its standard capacity increment is
* zero.
* 構造一個空向量,使其內部數據數組的大小為 10,其標准容量增量為零。
*/
public Vector() {
this(10);
}
/**
* Constructs a vector containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* 構造一個包含指定 collection 中的元素的向量,
* 這些元素按其 collection 的迭代器返回元素的順序排列。
*
*/
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);
}
/**
* Copies the components of this vector into the specified array.
* The item at index {@code k} in this vector is copied into
* component {@code k} of {@code anArray}.
* 將此向量的組件復制到指定的數組中。此向量中索引 k 處的項將復制到 anArray 的組件 k 中。
* 將數組Vector的全部元素都拷貝到數組anArray中
*/
public synchronized void copyInto(Object[] anArray) {
System.arraycopy(elementData, 0, anArray, 0, elementCount);
}
/**
* 將當前容量值設為 = 實際元素個數
* 對此向量的容量進行微調,使其等於向量的當前大小。
*/
public synchronized void trimToSize() {
modCount++; //Vector的改變統計數+1
int oldCapacity = elementData.length;
if (elementCount < oldCapacity) {
elementData = Arrays.copyOf(elementData, elementCount);
}
}
/**
* 增加此向量的容量(如有必要),以確保其至少能夠保存最小容量參數指定的組件數。
*
* @param minCapacity the desired minimum capacity
* minCapacity 所需的最小容量
*/
public synchronized void ensureCapacity(int minCapacity) {
if (minCapacity > 0) {
modCount++;
ensureCapacityHelper(minCapacity);//確認“Vector容量”的幫助函數
}
}
/**
* 這實現了ensureCapacity的不同步語義。
* 此類中的同步方法可以在內部調用此方法以確保容量,而不會導致額外同步的成本。
*
*/
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
*最大值 -8 ,防止OutOfMemoryError
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//Vector容量是否增加。
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);
}
//hugeCapacity 巨大容量 最大容量 Integer.MAX_VALUE
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* Sets the size of this vector. If the new size is greater than the
* current size, new {@code null} items are added to the end of
* the vector. If the new size is less than the current size, all
* components at index {@code newSize} and greater are discarded.
* 設置此向量的大小。如果新大小大於當前大小,則會在向量的末尾添加相應數量的 null 項。
* 如果新大小小於當前大小,則丟棄索引 newSize 處及其之后的所有項。
* @param newSize the new size of this vector
* @throws ArrayIndexOutOfBoundsException if the new size is negative 負數的話,拋出異常
*/
public synchronized void setSize(int newSize) {
modCount++;
if (newSize > elementCount) {
ensureCapacityHelper(newSize);
} else {
for (int i = newSize ; i < elementCount ; i++) {
elementData[i] = null;
}
}
elementCount = newSize;
}
/**
* 返回此向量的當前容量。 若新初始化
* Vector<String> v = new Vector<String>();
* v.capacity 返回為10
* v.size 返回為 0
*/
public synchronized int capacity() {
return elementData.length;
}
/**
* Returns the number of components in this vector.
* 返回此向量中的組件數。 Vector中數組的元素大小!
* @return the number of components in this vector
*/
public synchronized int size() {
return elementCount;
}
/**
* Tests if this vector has no components.
* 測試此向量是否不包含組件(元素)
* 當且僅當此向量沒有組件(元素)(也就是說其大小為零)時返回 true;否則返回 false。
*/
public synchronized boolean isEmpty() {
return elementCount == 0;
}
/**
* 返回此向量的組件的枚舉。返回的 Enumeration 對象將生成此向量中的所有項。
* 生成的第一項為索引 0 處的項,然后是索引 1 處的項,依此類推。
* (1)
* for(Enumeration<String> elements = v.elements();elements.hasMoreElements() ;)
* System.out.printf(elements.nextElement());
* (2)
* while(elements.hasMoreElements())
* System.out.printf(elements.nextElement());
*/
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
/**
* 如果此向量包含指定的元素,則返回 true。
* 更確切地講,當且僅當此向量至少包含一個滿足 (o==null ? e==null : o.equals(e)) 的元素 e 時,
* 返回 true。
*
*/
public boolean contains(Object o) {
return indexOf(o, 0) >= 0;
}
/**
* 返回此向量中第一次出現的指定元素的索引,如果此向量不包含該元素,則返回 -1。
* 更確切地講,返回滿足 (o==null ? get(i)==null : o.equals(get(i))) 的最低索引 i;
* 如果沒有這樣的索引,則返回 -1。
*/
public int indexOf(Object o) {
return indexOf(o, 0);
}
/**
* 返回此向量中第一次出現的指定元素的索引,從 index 處正向搜索,
* 如果未找到該元素,則返回 -1。更確切地講,
* 返回滿足 (i >= index && (o==null ? get(i)==null : o.equals(get(i)))) 的最低索引 i;
* 如果沒有這樣的索引,則返回 -1。
*/
public synchronized int indexOf(Object o, int index) {
//分為null和不為null
if (o == null) {
for (int i = index ; i < elementCount ; i++)//從index處正向搜索,默認從索引為0處開始
if (elementData[i]==null)
return i;
} else {
for (int i = index ; i < elementCount ; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**
* 返回此向量中最后一次出現的指定元素的索引;如果此向量不包含該元素,則返回 -1。
* 更確切地講,返回滿足 (o==null ? get(i)==null : o.equals(get(i))) 的最高索引 i;
* 如果沒有這樣的索引,則返回 -1。
*/
public synchronized int lastIndexOf(Object o) {
return lastIndexOf(o, elementCount-1);
}
/**
* 返回此向量中最后一次出現的指定元素的索引,從 index 處逆向搜索,如果未找到該元素,則返回 -1。
* 更確切地講,返回滿足 (i <= index && (o==null ? get(i)==null : o.equals(get(i)))) 的最高索引 i;
* 如果沒有這樣的索引,則返回 -1。
*/
public synchronized int lastIndexOf(Object o, int index) {
if (index >= elementCount)
throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
if (o == null) {
for (int i = index; i >= 0; i--)//從index處正向搜索,默認從索引為elementCount-1處開始
if (elementData[i]==null)
return i;
} else {
for (int i = index; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**
* 返回指定索引處的組件。
* 此方法的功能與 get(int) 方法的功能完全相同(后者是 List 接口的一部分)
*/
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return elementData(index);//按照下標去查找元素
}
/**
* 返回此向量的第一個組件(位於索引 0) 處的項)。
*/
public synchronized E firstElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(0);
}
/**
* 向量的最后一個組件,即索引 size() - 1 處的組件。
*/
public synchronized E lastElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(elementCount - 1);
}
/**
* 將此向量指定 index 處的組件設置為指定的對象。丟棄該位置以前的組件(元素)。
* 索引必須為一個大於等於 0 且小於向量當前大小的值。
*/
public synchronized void setElementAt(E obj, int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elementData[index] = obj;
}
/**
* 刪除指定索引處的組件。此向量中的每個索引大於等於指定 index 的組件都將下移,
* 使其索引值變成比以前小 1 的值。此向量的大小將減 1。
*
* 索引必須為一個大於等於 0 且小於向量當前大小的值。
*/
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 讓gc做它的工作*/
}
/**
* 將指定對象作為此向量中的組件插入到指定的 index 處。
* 此向量中的每個索引大於等於指定 index 的組件都將向上移位,使其索引值變成比以前大 1 的值
*/
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++;
}
/**
* 將指定的組件添加到此向量的末尾,將其大小增加 1。
* 如果向量的大小比容量大,則增大其容量。
*/
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);//判讀容量大小,是否需要增容
elementData[elementCount++] = obj; //默認添加
}
/**
* 從此向量中移除變量的第一個(索引最小的)匹配項。
* 如果在此向量中找到該對象,那么向量中索引大於等於該對象索引的每個組件都會下移,
* 使其索引值變成比以前小 1 的值
*/
public synchronized boolean removeElement(Object obj) {
modCount++;
int i = indexOf(obj); //查詢obj索引位置
if (i >= 0) {
removeElementAt(i); //移除變量的第一個匹配項
return true;
}
return false;
}
/**
* 從此向量中移除全部組件,並將其大小設置為零。
*/
public synchronized void removeAllElements() {
modCount++;
// Let gc do its work
for (int i = 0; i < elementCount; i++)
elementData[i] = null; //全部設置為 null
elementCount = 0; // elementCount大小設置為 0
}
/**
* 返回向量的一個副本。副本中將包含一個對內部數據數組副本的引用,
* 而非對此 Vector 對象的原始內部數據數組的引用。
*/
public synchronized Object clone() {
try {
@SuppressWarnings("unchecked")
Vector<E> v = (Vector<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, elementCount);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
/**
* Returns an array containing all of the elements in this Vector
* in the correct order.
* 返回一個數組,包含此向量中以恰當順序存放的所有元素。
* @since 1.2
*/
public synchronized Object[] toArray() {
return Arrays.copyOf(elementData, elementCount);
}
/**
* 返回一個數組,包含此向量中以恰當順序存放的所有元素;返回數組的運行時類型為指定數組的類型。
*/
@SuppressWarnings("unchecked")
public synchronized <T> T[] toArray(T[] a) {
if (a.length < elementCount)
return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
System.arraycopy(elementData, 0, a, 0, elementCount);
if (a.length > elementCount)
a[elementCount] = null;
return a;
}
// Positional Access Operations
// 定位訪問操作
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* 返回向量中指定位置的元素。
*/
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(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;
}
/**
* 將指定元素添加到此向量的末尾。
*/
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
/**
* 移除此向量中指定元素的第一個匹配項,如果向量不包含該元素,則元素保持不變。
* 更確切地講,移除其索引 i 滿足 (o==null ? get(i)==null : o.equals(get(i))) 的元素(如果存在這樣的元素)。
*/
public boolean remove(Object o) {
return removeElement(o);
}
/**
* 在此向量的指定位置插入指定的元素。將當前位於該位置的元素(如果有)
* 及所有后續元素右移(將其索引加 1)。
*/
public void add(int index, E element) {
insertElementAt(element, index);
}
/**
* 移除此向量中指定位置的元素。將所有后續元素左移(將其索引減 1)。
* 返回此向量中移除的元素。
*/
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;
}
/**
* 從此向量中移除所有元素。此調用返回后,向量將為空(除非拋出了異常)。
*/
public void clear() {
removeAllElements();
}
// Bulk Operations
// 批量操作
/**
* 如果此向量包含指定 Collection 中的所有元素,則返回 true。
*/
public synchronized boolean containsAll(Collection<?> c) {
return super.containsAll(c);
}
/**
* 將指定 Collection 中的所有元素添加到此向量的末尾,按照指定 collection 的迭代器所返回的順序添加這些元素。
*
*/
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;
}
/**
* 從此向量中移除包含在指定 Collection 中的所有元素。
*/
public synchronized boolean removeAll(Collection<?> c) {
return super.removeAll(c);
}
/**
* 在此向量中僅保留包含在指定 Collection 中的元素。
* 換句話說,從此向量中移除所有未包含在指定 Collection 中的元素。
*/
public synchronized boolean retainAll(Collection<?> c) {
return super.retainAll(c);
}
/**
* 在指定位置將指定 Collection 中的所有元素插入到此向量中。
* 將當前位於該位置的元素(如果有)及所有后續元素右移(增大其索引值)。
*/
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;
}
/**
* 比較指定對象與此向量的相等性。
*/
public synchronized boolean equals(Object o) {
return super.equals(o);
}
/**
* 返回此向量的哈希碼值。
*/
public synchronized int hashCode() {
return super.hashCode();
}
/**
* 返回此向量的字符串表示形式,其中包含每個元素的 String 表示形式。
*/
public synchronized String toString() {
return super.toString();
}
/**
* 返回此 List 的部分視圖,元素范圍為從 fromIndex(包括)到 toIndex(不包括)。
*/
public synchronized List<E> subList(int fromIndex, int toIndex) {
return Collections.synchronizedList(super.subList(fromIndex, toIndex),
this);
}
/**
* 從此 List 中移除其索引位於 fromIndex(包括)與 toIndex(不包括)之間的所有元素
*/
protected synchronized void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = elementCount - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
int newElementCount = elementCount - (toIndex-fromIndex);
while (elementCount != newElementCount)
elementData[--elementCount] = null;
}
/**
* 將Vector實例的狀態保存到流(即,序列化它)。 此方法執行同步以確保序列化數據的一致性。
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
final java.io.ObjectOutputStream.PutField fields = s.putFields();
final Object[] data;
synchronized (this) {
fields.put("capacityIncrement", capacityIncrement);
fields.put("elementCount", elementCount);
data = elementData.clone();
}
fields.put("elementData", data);
s.writeFields();
}
/**
* 對列表中的元素返回一個列表迭代器(以正確的順序),
* 從列表中指定的位置開始。 指定的索引指示由初始調用返回到next的第一個元素。
* 對上一個的初始調用將返回具有指定索引減1的元素。
*
*返回的列表迭代器是fail-fast的。
*
*/
public synchronized ListIterator<E> listIterator(int index) {
if (index < 0 || index > elementCount)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
/**
* 返回此列表中的元素(按正確順序)的列表迭代器。
*
* 返回的列表迭代器是fail-fast的。
*
*/
public synchronized ListIterator<E> listIterator() {
return new ListItr(0); //ListItr extends Itr implements ListIterator<E>
}
/**
* 返回此列表中的元素(按正確順序)的列表迭代器。
*
* 返回的列表迭代器是fail-fast的。
*/
public synchronized Iterator<E> iterator() {
return new Itr(); //class Itr implements Iterator<E>
}
/**
* An optimized version of AbstractList.Itr
* 這個下面不在分析,大概實現了要Iterator ,實現具體的一些方法
*/
private class Itr implements Iterator<E> {
}
}
5.總結
1: Vector實際上是通過一個數組去保存數據的。當我們構造Vecotr時;若使用默認構造函數,則Vector的默認容量大小是10。
2: 當Vector容量不足以容納全部元素時,Vector的容量會增加。若容量增加系數 大於0,則將容量的值增加“容量增加系數”;否則,將容量大小增加一倍。
3: Vector的克隆函數,即是將全部元素克隆到一個數組中。
4: 很多方法都加入了synchronized同步語句,來保證線程安全。
5: 同樣在查找給定元素索引值等的方法中,源碼都將該元素的值分為null和不為null兩種情況處理,Vector中也允許元素為null。
6: 遍歷Vector,使用索引的隨機訪問方式最快,使用迭代器最慢。
7: Vector很多地方都與ArrayList實現大同小異,現在已經基本不再使用。
歡迎訪問我的csdn博客,我們一同成長!
"不管做什么,只要堅持下去就會看到不一樣!在路上,不卑不亢!"
