ArrayList源码
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};//常量 空数组
transient Object[] elementData; //对象数组
public ArrayList(){
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
-----------------------------------------------
private int size; //默认为0
private static final int DEFAULT_CAPACITY = 10;
public boolean add(E e){
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return ture;
}
private void ensureCapacityInternal(int minCapacity){
if(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
minCapacity = Math.max(DEFAUL_CAPACITY,minCapacity); //默认大小(10)和1比较求最大值
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity){
if(minCapacity - elementData.length >0) //10-0
grow(minCapacity);
}
重点:扩容代码
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //很大
private void grow(int minCapacity){
int oldCapacity = elementData.length; //0
int newCapacity = oldCapacity + (oldCapacity >> 1); //0
if(newCapacity - minCapacity <0) //0-10 < 0
newCapacity = minCapacity; //10
if(newCapacity - MAX_ARRAY_SIZE >0) //10-很大
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData,newCapacity); //将新容量copy旧容量
}
ArrayList
1.实现原理:采用动态对象数组实现,默认构造方法创建一个空数组,
2.第一次添加元素,扩充容量为10,之后的扩充算法:原来数组大小+原来数组的一半(1.5倍)
3.不适合进行删除或插入操作
4.为了防止数组动态扩充次数过度,建议创建ArrayList时,给定初始容量
5.线程不安全,适合单线程访问时使用
JDK1.2开始
Vector
protected Object[] elementData;
public Vector(int initialCapacity){
this(initialCapacity,0);
}
public Vector(){
this(10);
}
public synchronized boolean add(E e){
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity){ //11
if(minCapacity - elementData.length > 0) 11 -10
grow(minCapacity);
}
protected int capacityIncrement; //默认为0
public Vector(int initialCapacity,int capacityIncrement){
super();
if(initialCapacity <0)
throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
private void grow(int minCapacity){
int oldCapacity = elementData.length; //10
int newCapacity = oldCapacity + ((capacityIncrement > 0)?capacityIncrement:oldCapacity);
if(newCapacity - minCapacity <0)
newCapcity = minCapacity;
if(newCapacity - MAX_ARRAY_SIZE >0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData,newCapacity);
}
1.实现原理,采用动态对象数组实现,默认构造方法创建了一个大小为10的对象数组
2.扩充的算法:当增量为0时,扩充为原来大小的2倍,当增量大于0时,扩充为原来大小+增量
3.不适合删除或插入操作
4.为了防止数组动态扩充次数过多,建议创建Vector时,给定初始容量
5.线程安全,适合在多线程访问时使用,效率较低