本帖最后由 张洪慊 于 2013-4-15 16:44 编辑
你这问题够"狠",哈哈,我查看了下源代码,关键位置分析了下,
如果需要更细节的->你可以去查看源文件:
private transient Object[] elementData;
private int size;
protected transient int modCount = 0;//AbstractList类中
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList() {
this(10);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;//old=10
int newCapacity = oldCapacity + (oldCapacity >> 1);//newCapacity=10+10/2=15
if (newCapacity - minCapacity < 0)//15-11>0->不执行
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)//15-Integer.MAX_VALUE - 8<0 不执行
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//Arrays类中的方法
} //public static <T> T[] copyOf(T[] original,int newLength)
//将产生一个新的数组:元素是elementData中的元素,长度是newCapacity
//发现它又重新赋值给了elementData->即elementData指向新数组
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//句话当11-10>0时
grow(minCapacity);//grow(11)->扩充
}
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e; //当size=10时,size+1=11
return true;
}
|