Difference between Vector and ArrayList in Java, vectorarraylist
First, we can see that both of these classes implement the List interface, and the List interface has three implementation classes: ArrayList, Vector, and sorted List. List is used to store multiple elements, maintain the order of elements, and allow repeated elements. The differences between the three implementation classes are as follows:
Check the Java source code and find that when the array size is not enough, you need to re-create the array and copy the elements to the new array. The size of the extended array of ArrayList and Vector is different.
In ArrayList:
1 public boolean add (E e) {2 3 ensureCapacity (size + 1); // add elements to determine whether they can be accommodated. If not, create an array 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; // This row is useless, I don't know why the developer considers 20 21 int newCapacity = (oldCapacity * 3)/2 + 1; // increase the size of the new array 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
The differences between ArrayList and Vector are as follows: