This article mainly compares the difference between 1.7 and 1.8 when adding elements. There is no detailed introduction to deletion and update. At the end of this article, two excellent articles will be presented to introduce JDK1.8 in detail.

JDK1.8 interpretation

Let’s take a look at the inheritance diagram of ArrayList



ArrayList implements List, RandomAccess, Cloneable, Serializable interfaces, etc.



ArrayList can have duplicate elements, and the elements can be null.

Implementation of RandomAccess: support random fast access, but the interface does not define any logic, ArrayList underlying data structure is an array, so it can be accessed quickly;



Cloneable: indicates that shallow copy is supported.

Implementation Serializable: Indicates that serialization can be implemented.

The global variable




The constructor



More on constructors:

// Default constructor publicArrayList() {
     //创建空列表,并不像1.7创建对象就实例化,更像一个懒加载
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    //指定初始容量参数的构造函数
    public ArrayList(int initialCapacity) {
    // 容量大于0
        if(initialCapacity > 0) {// Create an array of the specified size this.elementData = new Object[initialCapacity]; }else if(initialCapacity == 0) {// Create an empty array of 10 capacity, this.elementData = EMPTY_ELEMENTDATA; }else{// throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity); }} // Constructs a list of the elements of the specified collection, in the order they are returned by the collection iterator. public ArrayList(Collection<? extends E> coll) { elementData = coll.toArray(); // If the set element number is not 0if((size = elementData.length) ! = 0) {// Col.toarray may not return an array of type Object, so add the following statement to determine, // use the reflection inside the getClass() to get the elementData classif(elementData.getClass() ! = Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }else{// replace this.elementData = EMPTY_ELEMENTDATA; }}Copy the code

Add elements to the ArrayList



Add the element and call the ensureCapacityInternal method



EnsureCapacityInternal calls ensureExplicitCapacity and then calls the grow method



// private int size; Public Boolean add(E E) {public Boolean add(E E) {ensureCapacityInternal(size + 1); ElementData [size++] = e;return true; } public void add(int index, E element) {// check index rangeCheckForAdd(index); ensureCapacityInternal(size + 1); System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } private void rangeCheckForAdd(int index) {if(index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } public void ensureCapacity(int minCapacity) { int minExpand = (elementData ! = DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;if (minCapacity > minExpand) {
                ensureExplicitCapacity(minCapacity);
            }
        }
        private static int calculateCapacity(Object[] elementData, int minCapacity) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
                return Math.max(DEFAULT_CAPACITY, minCapacity);
            }
            return minCapacity;
        }
        private void ensureCapacityInternal(int minCapacity) {
            ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
        }
        private void ensureExplicitCapacity(int minCapacity) {
            modCount++;
            if(minCapacity - elementData.length > 0) grow(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; Private void grow(int minCapacity) {oldCapacity = elementData.length; OldCapacity int newCapacity = oldCapacity + (oldCapacity >> 1); // If the length of the new array minus the number of elements is less than 0, the number of elements is the length of the new arrayif(newCapacity - minCapacity < 0) newCapacity = minCapacity; // The hugeCapacity method is called if the new array length is subtracted from the maximum defined array lengthif(newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); ElementData = array.copyof (elementData, newCapacity); } private static int hugeCapacity(int minCapacity) {// If the value is less than 0, an exception is thrownif(minCapacity < 0) throw new OutOfMemoryError(); // If the element is greater than the maximum length of the array, the maximum length of the array is returnedreturn (minCapacity > MAX_ARRAY_SIZE) ?
                    Integer.MAX_VALUE :
                    MAX_ARRAY_SIZE;
        }
Copy the code

The default array size is 0 if the initial array size is not set, for example:

ArrayList list =new ArrayList(); // Create object[] elementData with length {} instead of length 10 list.add(1); // Create a 10-length array when you add for the first time. Add element elementData[0] = new Integer(1).... to array list.add(11); The size of the expanded array is 1.5 times that of the original array, and the elements in the original array are copied to the new arrayCopy the code

Add elements:

If the array is empty, initialize an array of length 10. If the array is empty, initialize an array of length 10. It is added again until the array overflows, and the overflow is expanded. Each expansion is 1.5 times the length of the original array. Finally, use the array.copyof () method to copy the elements from the original array into the new array (shallow copy here).

It is recommended to use parameter constructors in development to reduce triggering capacity expansion mechanism and improve efficiency.

JDK1.7 interpretation

Take a look at the inheritance diagram of ArrayList



The constructor





Add elements:

Create an array with a length of 10. Then determine whether the new element will exceed the array size. If not, add the array size to reduce the array size. It is added again until the array overflows, and the overflow is expanded. Each expansion is 1.5 times the length of the original array. Finally, use the array.copyof () method to copy the elements from the original array into the new array (shallow copy here).

Conclusion: In JDK 1.7, ArrayList is used to create an array of size 10 first. In JDK 1.8, ArrayList is used to create an array of size 10 only when data is added.

Reference 1: github.com/wupeixuan/J…

Reference 2: blog.csdn.net/xfhy

Special attention: some excerpts of the text copyright belongs to the original author!!