Vector底层源码

1
2
3
4
5
public abstract class AbstractList<E> extends AbstractCollection<E>implementsList<E> {
//外部操作数
//涉及到元素个数变化(添加、删除、清空)时,外部操作数就会++
protected transient int modCount = 0;//3
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class Vector<E> extends AbstractList<E> implements List<E>{
//数据容器
protected Object[] elementData;//new Object[10]{"麻生希","椎名空","水菜丽".....}
//元素个数(类似于ArrayList中的size属性)
protected int elementCount;//3
//容量增量
protected int capacityIncrement;//0
//数组的最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

public Vector() {
this(10);
}

//initialCapacity - 10
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}

//initialCapacity - 10
//capacityIncrement - 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;
}

//e - 水菜丽
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}

//minCapacity - 11
private void ensureCapacityHelper(int minCapacity) {
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}

//minCapacity - 11
private void grow(int minCapacity) {
// oldCapacity - 10
int oldCapacity = elementData.length;
// newCapacity - 20
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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test01 {

public static void main(String[] args) {

//Vector<String> v = new Vector<>();
Vector<String> v = new Vector<>(100,20);

v.add("麻生希");
v.add("椎名空");
v.add("水菜丽");

}
}
  1. Vector的数据结构是什么?

    Object类型的一维数组

  2. Vector的默认容量是多少?

    10

  3. Vector的最大容量是多少?

    Integer.MAX_VALUE-8

  4. Vector的最大容量为什么是Integer.MAX_VALUE-8?

    -8的位置是为了存放数组的头部信息

  5. Vector的扩容机制?

    容量增量小于等于0时,扩容机制是原来长度的2倍

    容量增量大于0时,扩容机制是原来长度+容量增量

  6. ArrayList和Vector的区别是什么?

    扩容机制有区别(见第5题)

    ArrayList是线程不安全的

    Vector是线程安全的