[Reserved] ArrayList from source to see the realization of expansion

public class ArrayList<E> extends AbstractList<E> implements List<E>, 
RandomAccess, Cloneable, java.io.Serializable

ArrayList class derived from the abstract class AbstractList, implements List interface, a random access RandomAccess interfaces, cloning the Cloneable interfaces, serial interfaces Serializable.

In general, we tend to use Arraylist add an object without much consideration, directly add () without the need to worry about whether their capacity exceeds the limit, the reason is that Arraylist source, the realization of add () method will look before its capacity is enough , will not automatically 'expansion' and then perform the add () additional element, i.e., automatic expansion.

Let's add an empty array list elements begin to see how the source code is implemented.

List list = new ArrayList();
list.add("A");

First, List list = new ArrayList (); initializing an empty list array list, in particular ArrayList class source code:

public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

Initialize the ArrayList object at the same time creates a default empty Object array variable elementData. Then list.add ( "A") corresponds to add the source () method:

 

As shown therein, public boolean add (E e) {} method performs modCount ++; then call add (e, elementData, size) method, and finally return boolean ture.

modCount to ArrayList defined as follows:

protected transient int modCount = 0;

doc Description:

/**
* The number of times this list has been <i>structurally modified</i>.
* Structural modifications are those that change the size of the
* list, or otherwise perturb it in such a fashion that iterations in
* progress may yield incorrect results....

Many structural change operations will be used modCount count array, the array is used to identify the number to be modified. For example add, set, remove the like.

 

Because it is the primary additive elements, it becomes the modCount ++ 1, the next step to add (e, elementData, size), this time to add the element e: "A", elementData as Object [] just created, size is the initial capacity of the array, a value of 0 (defined in an ArrayList: private int size, int type initially unassigned or 0)

Key facie add method implementation:

private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
}

Since the initial elementData.length == size == 0 is performed so as Grow () method returns the value assigned elementData.

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

There are two methods grow overloaded, no parameters grow () calls have grow ginseng, parameter size + 1.

private Object[] grow(int minCapacity) {
        return elementData = Arrays.copyOf(elementData, newCapacity(minCapacity));
    }

Here size + 1 = 1 as minCapacity, represents the minimum capacity, the actual well understood, because first of all I add a target minimum capacity required is the original length + 1, with the minimum capacity to the next step to add elements to operate, so by grow () to make sure the length of my arraylist object, that [expansion]

Arrays.copyOf expansion operation is achieved by a method:

Arrays.copyOf(elementData,newCapacity(minCapacity))

This method is copied directly into the original array elementData a new array of given length, and returns the new array object.

Then the new length of the array is how much? This is newCapacity defined (), let us look at:

private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity <= 0) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                return Math.max(DEFAULT_CAPACITY, minCapacity);
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return minCapacity;
        }
        return (newCapacity - MAX_ARRAY_SIZE <= 0)? newCapacity: hugeCapacity(minCapacity);
}

http://1.int oldCapacity = elementData.length

Because here it is elementData empty array, so oldCapacity == elementData.length == 0

2.newCapacity = oldCapacity + (oldCapacity >> 1)

This step is the core of the expansion operation, the length of the new array Capacity Capacity i.e. after the expansion of the original array + = original array / 2.

By oldCapacity >> 1 (Java shift operation by 2 bits to the right by 1) to achieve half of the capacity expansion of the original array

, I.e. ArrayList expansion is 1.5 times the original according to the capacity expansion.

But this time it newCapacity oldCapacity value 0 is also 0, ... Invalid expansion

3.if(newCapacity - minCapacity <=0)

After the second step newCapacity = 0, so that less than minCapacity = 1 into the following steps:

if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
    return Math.max(DEFAULT_CAPACITY, minCapacity);
if (minCapacity < 0) // overflow
    throw new OutOfMemoryError();
return minCapacity;

4.return Math.max(DEFAULT_CAPACITY, minCapacity);

ArrayList DEFAULT_CAPACITY to the initial default capacity, 10 size. It is defined as follows:

/**
 * Default initial capacity.
 */
private static final int DEFAULT_CAPACITY = 10;

return Math.max (DEFAULT_CAPACITY, minCapacity) returns the maximum and minCapacity 10, 10 directly back here

Now, after newCapacity () after the new array capacity is calculated to be 10, let us return to grow () in:

return elementData = Arrays.copyOf(elementData,newCapacity(minCapacity))

Arrays.copyOf elementData will be copied to a new Object 10 capacity of [] to go, and returns this array object elementData, finished in front of a lot of preparatory work, and after the implementation of expansion, and finally came to the add () method in the last two steps:

elementData [s] = e;

New elements are added to complete

size = s + 1;

The number of objects ArrayList +1

 

Guess you like

Origin www.cnblogs.com/smallwangmusk/p/11421232.html