Do you really understand ArrayList?

The underlying principle of ArrayList

array

​ 1. How to dynamically expand ArrayList?

  1. Use empty parameters to create a collection and create an array with a default length of 0 at the bottom;
  2. When adding the first element, the underlying layer will create an array with an array length of 10;
  3. When the storage is full, the array will automatically expand by 1.5 times;
  4. If 1.5 times the array length still cannot fit, the length of the newly created array should be the actual array length. For example, the current array length is 10, and if 100 elements are to be added, the required array length is 110;

2.Source code

    //transient 关键字修饰时,表示它不会被默认的序列化和反序列化机制所处理。
    transient Object[] elementData;

    //空参构造
    public ArrayList() {
    
    
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    //向数组添加元素,size则为下一个需要添加元素的位置
    private void add(E e, Object[] elementData, int s) {
    
    
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
    }

    //数组扩容的方法
    private Object[] grow(int minCapacity) {
    
    
        int oldCapacity = elementData.length;
        if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    
    
            int newCapacity = ArraysSupport.newLength(oldCapacity,
                    minCapacity - oldCapacity, /* minimum growth */
                    oldCapacity >> 1           /* preferred growth */);
            return elementData = Arrays.copyOf(elementData, newCapacity);
        } else {
    
    
            return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
        }
    }

    private Object[] grow() {
    
    
        return grow(size + 1);
    }

    public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
    
    
        // assert oldLength >= 0
        // assert minGrowth > 0

        int newLength = Math.max(minGrowth, prefGrowth) + oldLength;
        if (newLength - MAX_ARRAY_LENGTH <= 0) {
    
    
            return newLength;
        }
        return hugeLength(oldLength, minGrowth);
    }

    private static int hugeLength(int oldLength, int minGrowth) {
    
    
        int minLength = oldLength + minGrowth;
        if (minLength < 0) {
    
     // overflow
            throw new OutOfMemoryError("Required array length too large");
        }
        if (minLength <= MAX_ARRAY_LENGTH) {
    
    
            return MAX_ARRAY_LENGTH;
        }
        return Integer.MAX_VALUE;
    }

Guess you like

Origin blog.csdn.net/weixin_44749255/article/details/133203263