Java-----ArrayList Construction, add, remove, clear method to achieve the principle of source code Analysis __java

Source: Internet
Author: User
Tags object object throwable

I. Implementation within the ArrayList

ArrayList internal is achieved through the object[].


Two. SOURCE Analysis:

(1). Construction method

    Public ArrayList () {
        array = emptyarray.object;
    }

    public ArrayList (int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException ("Capacity < 0:" + C apacity);
        }
        Array = (capacity = 0?) EmptyArray.OBJECT:new object[capacity]);
    }

    Public ArrayList (collection<? extends e> Collection) {
        if (Collection = null) {
            throw new Nullpointerexc Eption ("collection = null");
        }
        Object[] A = Collection.toarray ();
        if (A.getclass ()!= object[].class) {
            object[] NewArray = new Object[a.length];
            System.arraycopy (A, 0, NewArray, 0, a.length);
            A = NewArray;
        }
        Array = A;
        size = A.length;
    }
ArrayList has 3 constructs method, first look first, array is a member variable, it is object[] type, when we are in new an empty parameter ArrayList, the system calls the object attribute in Emptyarray by default, The Emptyarray class is specifically implemented as follows:
public final class Emptyarray {private Emptyarray () {} public static final boolean[] Boolean =
    New Boolean[0];
    public static final byte[] byte = new byte[0];
    public static final char[] char = new char[0];
    public static final double[] double = new double[0];

    public static final int[] int = new INT[0];
    public static final class<?>[] Class = new Class[0];
    public static final object[] Object = new Object[0];
    public static final string[] String = new String[0];
    public static final throwable[] Throwable = new Throwable[0];
    public static final stacktraceelement[] stack_trace_element = new Stacktraceelement[0];
    public static final java.lang.reflect.type[] Type = new Java.lang.reflect.type[0];
public static final java.lang.reflect.typevariable[] type_variable = new Java.lang.reflect.typevariable[0]; }
As you can know from the Emptyarray class, when you use the method of constructing ArrayList null parameters by default, an empty array of ArrayList will be new object[0. Then look at the second construction method of ArrayList, first check the validity of parameters, when the incoming parameter is less than 0, will throw illegal parameter exception. If the argument is valid, the member variable array is assigned a ternary operation, and when capacity = 0 o'clock, the system generates an empty array by default, and the system generates an array of capacity length when capacity>0. Finally look at the third construction method, the first step to the validity of the input parameters test, if empty, then throw the null pointer exception; The second step converts the input collection to an array of arrays A, and the third determines whether the current array A is a object[] type, or, if not, creates an object type of The Copy method uses System.arraycopy, and then assigns the value to A; Step fourth assigns the converted array A to the member variable array; Step fifth assigns the length of the array to the member variable size.


(2). Add () method

/** * Adds The specified object at the end of this
     {@code ArrayList}.
     *
     @param Object
     * The            object to add.
     * @return always True
     *
    /@Override public boolean Add (E object) {
        object[] a = array;
        int s = size;
        if (s = = a.length) {
            object[] NewArray = new Object[s +
                    (S < (MIN_CAPACITY_INCREMENT/2)?
                     Min_capacity_increment:s >> 1)];
            System.arraycopy (A, 0, NewArray, 0, s);
            Array = a = NewArray;
        }
        A[s] = object;
        Size = s + 1;
        modcount++;
        return true;
    }
Here only the simple Add () method is analyzed, the first step is to assign the array, the set length to the local variables a and s, and the second to determine whether the length of the collection equals the length of the array, and if it is equal, redistribute the array and recalculate the amount of space allocated to the memory. Source computing the size of the memory space, using a ternary expression, when the length of the set is less than MIN_CAPACITY_INCREMENT/2, the system will allocate min_capacity_increment each length; When the length of the set is greater than the Min_capacity_ When INCREMENT/2, the system allocates half of the current length (s >>1 indicates that the current length moves one bit to the right, equivalent to S = S/2). The data of the array is then assigned to the new array, and the original array is updated.
private static final int min_capacity_increment = 12;
The third step is to add the incoming object object to the array subscript s; step fourth adds the current collection length to 1, and the fifth step Modcount, which is used to record the number of times the collection was modified (to determine whether a concurrent modification exception occurred).

(3). Remove () method

/** * Removes the object at the specified location from this list.
     * * @param index * The "object" to remove.
     * @return the removed object. * @throws Indexoutofboundsexception * When {@code location < 0 | | | location >= size ()} * *
        Override Public E-Remove (int index) {/** * 1. Local variable assignment */object[] A = array;
	int s = size; /** * 2. Determines whether the dropped subscript exceeds the length of the set, exceeding the thrown out of bounds exception/if (index >= s) {throwindexoutofboundsexception (index, S
        );
	 /** * 3. Gets the corresponding element of subscript index/@SuppressWarnings ("unchecked") E result = (e) a[index];
	 /** * 4. Move all elements that follow the subscript index forward one */system.arraycopy (A, index + 1, a, index,--s-index);  /** * 5. Set the last one to null to prevent memory leaks because an element was removed/a[s] = null;
	Prevent memory Leak/** * 6. Set length re-assigned * * size = s;
        /** * 7. Record modification times * * modcount++; return result;
    }
 

(4). Clear () method

    /**
     * Removes all elements from this {@code ArrayList}, leaving it empty.
     * *
     @see #isEmpty
     * @see #size
    /@Override public void Clear () {
        /**
       * To determine if the collection size is not equal to 0
       * *
        if (size!= 0) {
	     /**
	     * Populates the data elements of the array with
	     null
            /Arrays.fill (array, 0, size, null);
	     /**
	     * Set length to 0 *
            /size = 0;
	     /**
	     * Record number of
	     changes
            /modcount++
        }
    











Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.