一性锭、概念
矢量隊(duì)列孵班,繼承于AbstractList涉兽,實(shí)現(xiàn)了List, RandomAccess, Cloneable這些接口。
實(shí)現(xiàn)了List篙程;所以枷畏,它是一個(gè)列表,支持相關(guān)的添加虱饿、刪除拥诡、修改触趴、遍歷等功能。
實(shí)現(xiàn)了RandmoAccess接口渴肉,即提供了隨機(jī)訪問功能冗懦。
二、特點(diǎn)
- 線程安全
- 可以動(dòng)態(tài)擴(kuò)容/縮容
三仇祭、數(shù)據(jù)結(jié)構(gòu)
包含了3個(gè)成員變量:elementData , elementCount披蕉, capacityIncrement
- elementData 是"Object[]類型的數(shù)組",它保存了添加到Vector中的元素乌奇。
- elementCount 是動(dòng)態(tài)數(shù)組的實(shí)際大小没讲。
- capacityIncrement 是動(dòng)態(tài)數(shù)組的增長系數(shù)。
注意:
capacity(): int
size(): int
這兩個(gè)方法并不相同华弓,capacity表示當(dāng)前Vector可用容量食零,size表示當(dāng)前Vector中elements的數(shù)量,capacity >= size
四寂屏、實(shí)現(xiàn)要點(diǎn)
1. 實(shí)現(xiàn)方式上和ArrayList的異同點(diǎn)
相同點(diǎn):
實(shí)現(xiàn)原理和ArrayList一樣贰谣,使用數(shù)組Object[]來保存對象,通過size來明確當(dāng)前的對象(element)數(shù)目迁霎。
不同點(diǎn):
部分方法加了同步鎖synchronised
可以setSize(int): void吱抚,擴(kuò)容部分設(shè)置為null,縮容將多余部分拋棄
2. 擴(kuò)容與縮容原理
擴(kuò)容ensureCapacity考廉,每次嘗試增加capacityIncrement容量秘豹,capacityIncrement為0時(shí)直接擴(kuò)充為2倍,依然不夠時(shí)直接設(shè)置成需要的大小昌粤。
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);
}
縮容trimToSize既绕,提供外部調(diào)用
public synchronized void trimToSize() {
modCount++;
int oldCapacity = elementData.length;
if (elementCount < oldCapacity) {
elementData = Arrays.copyOf(elementData, elementCount);
}
}
3. 線程安全實(shí)現(xiàn)原理
分為三點(diǎn):
- public方法添加同步鎖synchronized
- subList返回的List使用Collections.synchronizedList生成,保證依然是線程安全的
- 自定義Iterator涮坐,方法中添加同步鎖synchronized
4. Enumeration
官方概念:
An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.
使用方式:
for (Enumeration E; e = v.elements(); e.hasMoreElements();){
System.out.println(e.nextElement());
}
評價(jià):
推薦優(yōu)先使用Iterator凄贩,因?yàn)镮terator支持更多操作比如remove(),名稱也更加簡潔
Vector中Enumeration實(shí)現(xiàn)原理
返回一個(gè)Enumeration對象袱讹,其中保存當(dāng)前指向的index疲扎,當(dāng)獲取元素時(shí),通過index獲取元素
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");
}
};
}