/**
* Constructs an empty list with an initial capacity of ten.
*/publicArrayList(){this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}//创建指定长度//大于0创建一个对应长度的Object数组//等于0就创建一个默认的空数组//否则抛出一个异常publicArrayList(int initialCapacity){if(initialCapacity >0){this.elementData =newObject[initialCapacity];}elseif(initialCapacity ==0){this.elementData = EMPTY_ELEMENTDATA;}else{thrownewIllegalArgumentException("Illegal Capacity: "+
initialCapacity);}}//publicArrayList(Collection<?extendsE> c){
elementData = c.toArray();if((size = elementData.length)!=0){// c.toArray might (incorrectly) not return Object[] (see 6260652)if(elementData.getClass()!= Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);}else{// replace with empty array.this.elementData = EMPTY_ELEMENTDATA;}}
添加方法
publicbooleanadd(E e){ensureCapacityInternal(size +1);// Increments modCount!!
elementData[size++]= e;returntrue;}//扩容入口privatevoidensureCapacityInternal(int minCapacity){ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}//计算最小容量privatestaticintcalculateCapacity(Object[] elementData,int minCapacity){//如果数组为空,返回默认容量和最小容量中的较大值if(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA){//默认容量10return Math.max(DEFAULT_CAPACITY, minCapacity);}return minCapacity;}privatevoidensureExplicitCapacity(int minCapacity){
modCount++;// overflow-conscious code//最小容量如果大于了当前数组的容量if(minCapacity - elementData.length >0)//扩容grow(minCapacity);}privatevoidgrow(int minCapacity){// overflow-conscious codeint oldCapacity = elementData.length;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);}
删除
public E remove(int index){//判断是否越界rangeCheck(index);
modCount++;//得到要删除的元素
E oldValue =elementData(index);//计算出需要移动覆盖的长度int numMoved = size - index -1;//拷贝数组,相当于将后面的数组元素全部往前移动1个位置if(numMoved >0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size]= null;// clear to let GC do its workreturn oldValue;}