首先看這兩類都實現List接口,而List接口一共有三個實現類,分別是ArrayList、Vector和LinkedList。List用於存放多個元素,能夠維護元素的次序,並且允許元素的重復。3個具體實現類的相關區別如下:
查看Java源代碼,發現當數組的大小不夠的時候,需要重新建立數組,然後將元素拷貝到新的數組內,ArrayList和Vector的擴展數組的大小不同。
ArrayList中:
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
Vector中:
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
關於ArrayList和Vector區別如下: