JDK1.0时候就有了Vector类,JDK1.2版本推出了List接口和ArrayList与LinkedList实现类,现在Vector不怎么使用。
ArrayList和Vector底层使用Object[]存储
LinkedList底层使用双向列表存储,对于平凡使用插入、删除操作的话效率更高
ArrayList线程不安全,所以效率高
Vector线程安全,所以效率较低
ArrayList源码分析
JDK7.0与JDK8.0创建底层Object[]的时间有所不同,JDK7.0的时候在调用空参构造器时就创建了长度为10的Object的数组,而JDK8.0在赋值的时候才创建数组。
7.0具体原码:
//带参构造器
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
//空参构造器
public ArrayList() {
this(10);
}
8.0具体原码:
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//判断长度是否超过
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//如果add后数组的长度超出了原长度会进行grow扩容,数组的长度扩容为原来的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}