JDK6源码分析: 底层就是一个Object类型的数组
private transient Object[] elementData;
private int size;
构造方法
// 默认创建10个元素的数组
public ArrayList() {
this(10);
}
// 指定个数的数组
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
// 根据数组个数超出就创建新数组把旧数组元素复制到新元素中
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
// 数组长度扩充1.5倍+1
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
//
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
// Arrays.copyof方法底层源码会根据原数组类型创建一个指定大小的新数组
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
// 增加新元素,底层数组长度+1并给数组末尾元素指定引用地址
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}