它是ArrayList的线程安全版本,其实现90%和ArrayList都完全一样,区别在于:
1、Vector是线程安全的,ArrayList是线程非安全的,代码示例:
public synchronized boolean add(E e) {
modCount
++;
ensureCapacityHelper(
elementCount
+ 1);
elementData
[
elementCount
++] =
e
;
return
true
;
}
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
;
}
2、Vector可以指定增长因子,如果该增长因子指定了,那么扩容的时候会每次新的数组大小会在原数组的大小基础上加上增长因子;如果不指定增长因子,那么就给原数组大小*2,源代码是这样的:
int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
capacityIncrement 变量是指定增长大小,默认为0,用户初始化时候可指定改变量大小
public
Vector() {
this
(10);
}
public
Vector
(
int
initialCapacity
) {
this
(
initialCapacity
, 0);
}
public
Vector(
int
initialCapacity
,
int
capacityIncrement
) {
super
();
if
(
initialCapacity
< 0)
throw
new
IllegalArgumentException(
"Illegal Capacity: "
+
initialCapacity
);
this
.
elementData
=
new
Object[
initialCapacity
];
this
.
capacityIncrement
=
capacityIncrement
;
}
ArrayList源代码是这样的,在原来的基础上默认增长1.5倍:
int newCapacity = oldCapacity + (oldCapacity >> 1);