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

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

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

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

public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

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

 private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

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

 private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

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

 private void grow(int minCapacity) {
        // overflow-conscious code
        int 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);
    }

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

public static  T[] copyOf(U[] original, int newLength, Class newType) {
        @SuppressWarnings("unchecked")
        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;
    }

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));

 

你可能感兴趣的:(ArrayList原理扩容解析(jdk1.8))