流程图:
add方法:
/**ArrayList的add方法有几个重载,最后会来到这个方法*/privatevoidadd(Ee, Object[] elementData, ints) { if (s==elementData.length) //判断是否需要扩容elementData=grow(); //如果需要扩容调用扩容方法elementData[s] =e; //将数据插入到数组尾size=s+1; //数组长度更新}
grow方法:
//add方法里调用的grow方法privateObject[] grow() { returngrow(size+1); } //实际调用的重载方法privateObject[] grow(intminCapacity) { //newCapacity就是获得新的容量//Arrays.copyOf是把之前的数组复制到新的数组里returnelementData=Arrays.copyOf(elementData,newCapacity(minCapacity)); }
newCapacity方法:
//获得扩容后容量privateintnewCapacity(intminCapacity) { intoldCapacity=elementData.length; //这句比较关键,新的容量=旧容量+旧容量右移1位(相当于除2)intnewCapacity=oldCapacity+ (oldCapacity>>1); //判断溢出的,不用管if (newCapacity-minCapacity<=0) { if (elementData==DEFAULTCAPACITY_EMPTY_ELEMENTDATA) returnMath.max(DEFAULT_CAPACITY, minCapacity); if (minCapacity<0) // overflowthrownewOutOfMemoryError(); returnminCapacity; } //如果不溢出就返回新容量,否则返回int类型上限2147483647-8return (newCapacity-MAX_ARRAY_SIZE<=0) ?newCapacity : hugeCapacity(minCapacity); }