ArrayList from 0 to 1

ArrayList is actually an array with variable length. Initially, it is an empty array. When the first element is added, the capacity of the array becomes 10.
The time complexity of inserting and deleting elements is O(n). Find the length of the table and add elements. The time complexity of taking the i-th element is O(1)

1. ArrayList data structure

//使用一个Object数组进行存储
 transient Object[] elementData;
 //数组元素的大小
 private int size;

2.add method

1. Add method without specified subscript

The following JDK source code

	//增加方法
   public boolean add(E e) {
    
    
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    //检查是否要扩容
    private void ensureCapacityInternal(int minCapacity) {
    
    
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    //得到最小扩容量
  	private static int calculateCapacity(Object[] elementData, int minCapacity) {
    
    
  		//返回默认容量和当前容器加1的最大值
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    
    
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    //判断是否需要扩容
	 private void ensureExplicitCapacity(int minCapacity) {
    
    
        modCount++;
        //容量超出即扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    //扩容
   private void grow(int minCapacity) {
    
    
   		//保存旧容量
        int oldCapacity = elementData.length;
        //新容量为旧容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //新容量是否小于最小需要容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
         //新容量是否超出了ArrayList所定义的最大容量
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
          //拷贝,ArrayscopyOf()继续调用System的arraycopy
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

Summary:
1. First judge whether to expand and then assign a value
2. Expand to 1.5 times the original array
3. Use the System copy method

2. Specify the add method of the subscript

   public void add(int index, E element) {
    
    
       //检查下标是否越界
        rangeCheckForAdd(index);
        //判断是否要扩容
        ensureCapacityInternal(size + 1);  
        //让index开始之后的所有成员后移一个位置:
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

The remove method is similar to the get method, except that the element is deleted and moved to the left

Guess you like

Origin blog.csdn.net/weixin_40791454/article/details/107040140