When explaining the difference between ArrayList and Vector, we have to mention List, so we review this, we can see this through the following chart:
What is the difference between ArrayList and the Vector is it?
Take a detailed analysis of the source code:
(1)ArrayList
ArrayList: three constructors, the default length of 10
//构造一个默认初始容量为10的List
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
//构造一个指定默认长度为list initialCapacity
public ArrayList(int initialCapacity) {
super();
if(initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity:"+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList(Collection<? extends E> c) {}
The main source added
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
modCount++;
//如果添加一个元素之后,新容器的大小大于容器的容量,那么就无法存值了,需要扩充空间
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //扩充的空间增加原来的50%(即是原来的1.5倍)
if (newCapacity - minCapacity < 0) //如果容器扩容之后还是不够,那么直接将minCapacity设为容器的大小
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) //如果扩充的容器太大了的话,那么就执行hugeCapacity
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
(2)Vector
Vector Constructor: four default length is 10
//构造一个指定默认长度的list
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
//构造一个默认初始容量为10的list
public Vector() {
this(10);
}
//构造一个包含collection 元素的list
public Vector(Collection<? extends E> c) {
...
}
//区别在于可以设置capacityIncrement
public Vector(int initialCapacity, int capacityIncrement) {
super();
...
}
The main source added:
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
/**
这个扩充需要做个判断:如果容量增量初始化的不是0,即使用的public Vector(int initialCapacity,int capacityIncrement)
构造方法进行的初始化,那么扩充的容量是(oldCapacity+capacityIncrement),就是原来的容量加上容量增量的值;
如果没有设置容量增量,那么扩充后的容量就是(oldCapacity+oldCapacity),就是原来容量的二倍。
**/
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
Benpian explain This is the end!
Source reference to https://blog.csdn.net/weixin_39684625/article/details/80652809
Thank the author of this article! thank!
thank you all! Please criticism and grow with us.