Arraylist:
(1)成员变量
// 默认的空数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA={};
// 实际存数据的数组
transientObject[]elementData;
// 默认容量
privatestaticfinalintDEFAULT_CAPACITY=10;
(2)构造器
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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection c) {
Object[] a = c.toArray();
if ((size = a.length) !=0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
}else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
}else {
// replace with empty array.
elementData =EMPTY_ELEMENTDATA;
}
}
(3)add方法
public boolean add(E e) {
// 确保能不能放进去
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 根据数组长度和传入的容量值计算容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
// 初始化时 就是空啊,他会选择10当他的容量值。
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {、
// 记录了集合被修改的次数
modCount++;
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 数组扩容的地方
private void grow(int minCapacity) {
// 获取旧的容量
int oldCapacity = elementData.length;
// 很明显扩容了1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 扩容后拷贝数据
elementData = Arrays.copyOf(elementData, newCapacity);
(4)查找和删除
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
// System.arraycopy
// Object src : 原数组
// int srcPos : 从元数据的起始位置开始
// Object dest : 目标数组
// int destPos : 目标数组的开始起始位置
// int length : 要copy的数组的长度
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null;
return oldValue;
}
2.注意:
transient=> 不需要进行序列化
1.ArrayList的构造器初始容量0 不是10。
第一次add元素 ,导致底层 数组大小 由0 -》 10