首先看这两类都实现List接口,而List接口一共有三个实现类,分别是ArrayList、Vector和LinkedList。List用于存放多个元素,能够维护元素的次序,并且允许元素的重复。3个具体实现类的相关区别如下:
1 public boolean add(E e) {
2
3 ensureCapacity(size + 1); // 增加元素,判断是否能够容纳。不能的话就要新建数组
4
5 elementData[size++] = e;
6
7 return true;
8
9 }
10
11 public void ensureCapacity(int minCapacity) {
12
13 modCount++;
14
15 int oldCapacity = elementData.length;
16
17 if (minCapacity > oldCapacity) {
18
19 Object oldData[] = elementData; // 此行没看出来用处,不知道开发者出于什么考虑
20
21 int newCapacity = (oldCapacity * 3)/2 + 1; // 增加新的数组的大小
22
23 if (newCapacity < minCapacity)
24
25 newCapacity = minCapacity;
26
27 // minCapacity is usually close to size, so this is a win:
28
29 elementData = Arrays.copyOf(elementData, newCapacity);
30
31 }
32
33 }
34
35
1 private void ensureCapacityHelper(int minCapacity) {
2
3 int oldCapacity = elementData.length;
4
5 if (minCapacity > oldCapacity) {
6
7 Object[] oldData = elementData;
8
9 int newCapacity = (capacityIncrement > 0) ?
10
11 (oldCapacity + capacityIncrement) : (oldCapacity * 2);
12
13 if (newCapacity < minCapacity) {
14
15 newCapacity = minCapacity;
16
17 }
18
19 elementData = Arrays.copyOf(elementData, newCapacity);
20
21 }
22
23 }
24
25