飞道的博客

ArrayList原理扩容解析(jdk1.8)

321人阅读  评论(0)

1.先模拟数组扩容需要的条件


  
  1. ArrayList<Object> list = new ArrayList<>();
  2. for( int i= 1;i<= 10;i++){
  3. list.add(i);
  4. }
  5. list.add( 1, "zhaoliu");

2.当开始添加第11个元素时,会调用add(index,element)方法,开始进行下标判断,调用ensureCapacityInternal方法,参数值为11


  
  1. public void add( int index, E element) {
  2. rangeCheckForAdd( index);
  3. ensureCapacityInternal(size + 1); // Increments modCount!!
  4. System.arraycopy(elementData, index, elementData, index + 1,
  5. size - index);
  6. elementData[ index] = element;
  7. size++;
  8. }

3.判断用不用赋初值,调用ensureExplicitCapacity方法,参数值为11


  
  1. private void ensureCapacityInternal(int minCapacity) {
  2. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  3. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  4. }
  5. ensureExplicitCapacity(minCapacity);
  6. }

4.判断是否需要扩容,minCapacity=11, elementData.length=10,判断成立,所以进入grow方法


  
  1. private void ensureExplicitCapacity(int minCapacity) {
  2. modCount++;
  3. // overflow-conscious code
  4. if (minCapacity - elementData.length > 0)
  5. grow(minCapacity);
  6. }

5. minCapacity=11,oldCapacity =10,newCapacity =15,直接进行数组复制,elementData 数组中已有的元素, newCapacity=15
 


  
  1. private void grow(int minCapacity) {
  2. // overflow-conscious code
  3. int oldCapacity = elementData.length;
  4. int newCapacity = oldCapacity + (oldCapacity >> 1);
  5. if (newCapacity - minCapacity < 0)
  6. newCapacity = minCapacity;
  7. if (newCapacity - MAX_ARRAY_SIZE > 0)
  8. newCapacity = hugeCapacity(minCapacity);
  9. // minCapacity is usually close to size, so this is a win:
  10. elementData = Arrays.copyOf(elementData, newCapacity);
  11. }

6.从下图得出copy=true,所以最后T[]copy为一个大小为15的数组


  
  1. public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
  2. @SuppressWarnings( "unchecked")
  3. T[] copy = (( Object)newType == ( Object) Object[].class)
  4. ? (T[]) new Object[newLength]
  5. : (T[]) Array.newInstance(newType.getComponentType(), newLength);
  6. System.arraycopy(original, 0, copy, 0,
  7. Math.min(original.length, newLength));
  8. return copy;
  9. }

7.进行数组的复制,original为原数组,copy为大小为15的空数组,Math.min(original.length, newLength)=10

那么意思就是,把原数组从下标0开始复制复制的大小是10.从copy中下标为0的位置开始

System.arraycopy(original, 0, copy, 0,Math.min(original.length, newLength));

 


转载:https://blog.csdn.net/loveking6/article/details/106722443
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场