JDK ArrayList source code interpretation __arraylist

Source: Internet
Author: User
Tags int size serialization shallow copy

After reading the copyonwritearraylist in 2017/02/16, I made a comment on some of the code in ArrayList. Found some details that were not noticed for the first time. I hope you will see some gains. —————

Looking at source code is a necessary skill for a programmer.
Here is to do first write a ArrayList source code interpretation. All the readings are written on the source code annotation, simple and similar to no longer repeat the comment.
Interpretation of the JDK version is 1.7.
I hope you can see the harvest.

2017/06/03 Update:
Key Knowledge Collection:

The default initialization capacity is 10;

The underlying implementation is actually an array, and when there is no object storage, it's actually an empty array.

The Add (), remove () in the iterator is reported as an exception because the method called Add () changes the Modcount, while the iteration determines whether the expected Modcount and actual modcount are consistent and the inconsistency throws an exception.

The maximum set size is integer.max_value-8 because some of the virtual machines hold some header fields in the array, at which point the maximum capacity is allocated Integer.max_value
can cause a outofmemoryerror error, that is, the requested array size exceeds the virtual machine limit.

The default capacity is 0.5 times times larger than the original volume per expansion. If the specified capacity is larger than the default expansion, the capacity is expanded by the specified size

ArrayList source code:


Package java.util; public class Arraylist<e> extends abstractlist<e> implements List<e>, Randomaccess, Cloneable, J

    ava.io.Serializable {private static final long serialversionuid = 8683452581122892189L;
     /** * Default initial capacity.

    * Default Initialization capacity * * private static final int default_capacity = 10;
     /** * Empty Array instance (this is returned when there is no data in ArrayList) * Shared empty array instance used for empty.

    * * private static final object[] Empty_elementdata = {};
    /** * ArrayList is stored in the object, but no object is stored, Elementdata = = Empty_elementdata * If the object is added, then the capacity will expand to default_capacity. * In addition, when serialized, the transient modified by the variable is not serialized, which is the role of serialization * Here is the reason for using transient: * Because ArrayList is actually a dynamic array, each time after filling up automatically to increase the set length value,
    If the array automatically grows to a length of 100, * but only one element is actually placed, then many null elements are serialized, so ArrayList sets Elementdata to transient.
     * and ArrayList rewrite WriteObject and ReadObject to achieve serialization and deserialization.
     * The array buffer into which the elements of the ArrayList are stored. * The capacity Of the ArrayList is the length of this array buffer. any * empty ArrayList with elementdata = = Empty_elementdata would be expanded to * default_capacity when the Firs
     t element is added.

    * Private transient object[] elementdata;
     /** * The size of the ArrayList (the number of elements it contains).

    * * @serial/private int size;
     /** * Constructs a empty list with the specified initial capacity. * * @param initialcapacity The initial capacity of the list * @throws illegalargumentexception if the Specifie
        D Initial capacity * is negative/public ArrayList (int initialcapacity) {super ();
                                               if (initialcapacity < 0) throw new illegalargumentexception ("illegal Capacity:" +
        initialcapacity);
    This.elementdata = new Object[initialcapacity]; /** * Constructs an empty ArrayList instance, but there is no capacity in this space-time instance * constructs anEmpty list with an initial capacity of ten.
        * * Public ArrayList () {super ();
    This.elementdata = Empty_elementdata;
    /** * If C is a collection that is converted through the Arrays.aslist () method, such as the following code:list<string> List = arrays.aslist ("abc"); * Then the output list.getclass () is visible as: Class Java.util.arrays$arraylist * If the List.toarray () is then given to object [] Objectarray,
    Output ObjectArray.class:class [Ljava.lang.String;
    * So, at this time objectarray[0] = new Object (); The store exception is reported. Therefore, if you find that Elementdata.getclass is not the same as object[].class, you need to create a object[. * Note that if the list<string> list = Arrays.aslist ("abc") is changed to list<string> list = Lists.newarraylist () There will be no problem * Also, see 6 260652 of 6260652 refers to the JDK's bug number. can go to the official website to see the bug details * The code example is as follows:/** * Normal * * list<string> List = new Arraylist<string&gt
        ;();
        List.add ("ASD");
        Object[] objects = List.toarray ();

        Objects[0] = new Object ();
        /** * ERROR * * list<string> listerror = arrays.aslist ("abc");object[] Objects1 = Listerror.toarray ();

     Objects1[0] = new Object (); * Constructs a list containing the elements of the specified * collection, in the order they are to returned by the Coll
     Ection ' s * iterator.  * * @param c The collection whose elements are to is placed into this list * @throws NullPointerException if the Specified collection is null */public ArrayList (collection<? extends e> c) {elementdata = C.toar
        Ray ();
        size = Elementdata.length;
            C.toarray might (incorrectly) not return object[] (= 6260652) if (Elementdata.getclass ()!= object[].class)
    Elementdata = arrays.copyof (elementdata, size, object[].class); The/** *size is the size of the actual storage in ArrayList, and Elementdata is an array whose length is the *capacity that can be assigned at creation time to adjust the capacity of this ArrayList instance to the current storage of the list
    Size.
    * and Modcount is the protected field inherited from Abstractlist, representing the number of times this list has been modified from the ArrayList. * Fast failures in iterators are provided by Modcount, specifically: If a subclass wants to provide a fast-fail iterator (and a list iterator), it simply needs to add (inAdd this field to the T, E) and remove (int) * methods (and any other methods that it overrides that cause changes to the list structure). This field cannot be added to more than 1 in a single call to add (int, E) or remove (int) *, otherwise the iterator (and list iterator) throws a false *concurrentmodificationexceptions. 
    If an implementation does not want to provide a quick fail iterator, you can omit this field.  * * Trims The capacity of this <tt>ArrayList</tt> instance to is the * list ' s current size.
     An application can-operation to minimize * storage of <tt>ArrayList</tt> instance.
        * * public void TrimToSize () {modcount++;
        if (Size < elementdata.length) {Elementdata = arrays.copyof (elementdata, size);
    }/** * Modifies the capacity of the ArrayList to mincapacity * If it is an empty table, then call Ensurecapacity can set a capacity of 0 larger at will. * If it is not an empty table, such as by ArrayList (int initcapacity) to initialize the capacity, then call *ensurecapacity if the mincapacity is less than the default capacity, then do not reset * (Note: personal feeling can The default_capacity becomes Math.max (This.size (), default_capacity)) * Increases the CAPACITY of this <tt>ArrayList< /tt> instance, if * necessary, to ensure that it can hoLD at least the number of elements * specified by the minimum capacity argument.
        * * @param mincapacity the desired minimum capacity * * public void ensurecapacity (int mincapacity) { int minexpand = (elementdata!= empty_elementdata)//any size if real element table? 0//larger than default for empty table.
            It ' s already supposed to be//at default size.

        : default_capacity;
        if (Mincapacity > Minexpand) {ensureexplicitcapacity (mincapacity);
            } private void ensurecapacityinternal (int mincapacity) {if (Elementdata = = Empty_elementdata) {
        mincapacity = Math.max (default_capacity, mincapacity);
    } ensureexplicitcapacity (mincapacity);  /** *elementdata Array, has determined the size, if the contraction, may overflow, so can only capacity/private void ensureexplicitcapacity (int mincapacity)

        {modcount++;
 Overflow-conscious Code       if (mincapacity-elementdata.length > 0) grow (mincapacity); /** * Maximum collection size, the meaning of using integer.max_value-8 is: * Some virtual machines save some header fields in the array, then to allocate the maximum capacity of Integer.max_value * can cause Outofmemor
     Yerror error, that is, the requested array size exceeds the virtual machine limit.
     * The maximum size of array to allocate.
     * Some VMs Reserve Some header words in an array.
    * Attempts to allocate larger arrays could result in * outofmemoryerror:requested array size exceeds VM limit * *

    private static final int max_array_size = integer.max_value-8; /** * Default capacity of 0.5 times times the original volume of expansion. If the specified capacity is larger than the default expansion, expand by the specified capacity * If the capacity to be expanded is larger than the maximum capacity, then the call Hugecapacity () uses the specified capacity compared to the maximum capacity, * if the specified capacity is larger than the maximum capacity, then return Integer.max_
     Value for expansion. * Increases the capacity to ensure, it can hold at least the * number of elements specified by the minimum Capaci
     Ty argument. * * @param mincapacity the desired minimum capacity * * private void grow (int mincapacity) {//Overf low-conscious Code int oldcapacity = elementdata.length;
        int newcapacity = oldcapacity + (oldcapacity >> 1);
        if (newcapacity-mincapacity < 0) newcapacity = mincapacity;
        if (newcapacity-max_array_size > 0) newcapacity = hugecapacity (mincapacity);
    Mincapacity is usually the close to size, so this is a win:elementdata = arrays.copyof (Elementdata, newcapacity); private static int hugecapacity (int mincapacity) {if (mincapacity < 0)//overflow thro
        W new OutOfMemoryError ();
            Return (Mincapacity > Max_array_size)?
    Integer.MAX_VALUE:MAX_ARRAY_SIZE;
     }/** * Returns the number of elements in this list.
    * * @return The number of elements in this list */public int size () {return size;
     }/** * Returns <tt>true</tt> If this list contains no elements. * * @return <tt>true</tt> if this list contAins no Elements * * Public boolean IsEmpty () {return size = = 0;
     }/** * Returns <tt>true</tt> If this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * At least one element <tt&gt ;e</tt> such that * <tt> (o==null&nbsp;?
     &nbsp;e==null&nbsp;:&nbsp;o.equals (e)) </tt>. * * @param o element whose presence in this list are to tested * @return <tt>true</tt> if this LIS
    T contains the specified element */public Boolean contains (Object o) {return indexOf (O) >= 0; }/** * Returns the index of the ' the ' of the ' the ' of the ' the specified element * in this list, or-1 if this Li
     St does not contain the element. * More formally, returns of the lowest index <tt>i</tt> such that * <tt> (o==null&nbsp;? &nbsp;get (i) ==null&nbsp;:&nbsp;o.equaLS (get (i)) </tt&gt, * or-1 If there is no such index.
                */public int indexOf (Object o) {if (o = = null) {for (int i = 0; i < size; i++)
        if (elementdata[i]==null) return i; else {for (int i = 0; i < size; i++) if (O.equals (elementdata[i)) r
        Eturn i;
    } return-1; }/** * Returns The index of the last occurrence of the specified element * in this list, or-1 if this LIS
     T does not contain the element. * More formally, returns of the highest index <tt>i</tt> such that * <tt> (o==null&nbsp;?
     &nbsp;get (i) ==null&nbsp;:&nbsp;o.equals (get (i)) </tt>, * or-1 If there is no such index.
                */public int lastindexof (Object o) {if (o = = null) {for (int i = size-1; I >= 0; i--)
 if (elementdata[i]==null) return i;       else {for (int i = size-1 i >= 0; i--) if (O.equals (elementdata[i))
        return i;
    } return-1;
    /** * Here cloning is a shallow clone, although the Elementdata is arrays.copyof out, that is, the array is new, * But the element references in the array are old.
        * Code Test instance: (for convenience, the attribute is defined directly as public) stringutiltest StringUtilTest1 = new Stringutiltest ();
        Stringutiltest stringutiltest = new Stringutiltest ();
        Stringutiltest.age = 999;

        Stringutiltest1.age = 999;
        arraylist<stringutiltest> stringutiltestlist = new arraylist<stringutiltest> (4);
        Stringutiltestlist.add (stringutiltest);

        Stringutiltestlist.add (STRINGUTILTEST1);
        arraylist<stringutiltest> clone = (ArrayList) stringutiltestlist.clone ();

        Clone.get (0). Age = 111;
        System.out.println ("list:" +stringutiltestlist);
        System.out.println ("Clone:" +clone);
    System.out.println (clone.get (1) = = Stringutiltestlist.get (1)); * Output Result: List:[stringutiltest{age=111}, stringutiltest{age=999}] clone:[stringutiltest{age=111}, StringUtilTest{age=999}]  True * Returns A shallow copy of this <tt>ArrayList</tt> instance.
     (the * elements themselves are not copied.) 
            * @return A clone of this <tt>ArrayList</tt> instance */Public Object clone () {try {
            @SuppressWarnings ("unchecked") arraylist<e> v = (arraylist<e>) super.clone ();
            V.elementdata = arrays.copyof (elementdata, size);
            V.modcount = 0;
        return v; catch (Clonenotsupportedexception e) {//This shouldn ' t happen, since we are cloneable throw NE
        W Internalerror ();  }/** * Returns An array containing all of the elements in this list * into proper sequence (from the
     To the last element). * <p>the returned array would be ' safe ' in ' no references to IT are * maintained by this list.  (In the other words, this method must allocate * a new array).
     The caller is thus free to modify the returned array.
     * <p>this method acts as bridge between Array-based and collection-based * APIs.  * * @return An array containing all of the "elements in" * Proper sequence * * public
    Object[] ToArray () {return arrays.copyof (elementdata, size);
    /** * If the length of a is not large enough, then obviously the elements in the elementdata cannot be put into the array all at this time no longer use a.length as the copy capacity, but use size.
    * If the a.length is not smaller than size, then directly copy to a above, copy the length of size, because the actual size of the elementdata *, if the a.length is larger than size, obviously there is excess space in a, then set at A[size] * is null to determine the actual size. 
     (This method is used to determine the length of a list only if the caller knows that the list does not contain any null elements). * Returns an array containing "all of the" elements in "this list in proper * sequence" (from a-to-last element);  The runtime type of the returned * array is the specified array. If the list fits in the * specified array, it is REturned therein.
     Otherwise, a new array is * allocated with the runtime type of the specified array and the size of * this list. * <p>if the list fits in the specified array with room to spare * (i.e., the array has more element s than the list), the element in * the array immediately following the "End of" collection is set to * <tt&  Gt;null</tt>. (This is useful in determining the length of the * list <i>only</i> if the caller knows that the list doe
     s not contain * any null elements.) * * @param a The array into which the elements of the ' list are to * being stored, if it is the big enough;
     Otherwise, a new array of the * same runtime type is allocated to this purpose. * @return An array containing the elements of the list * @throws arraystoreexception if the runtime type of the Speci
 Fied array * isn't a supertype of the runtime type of every element in    * This list * @throws NullPointerException If the specified array is null */@SuppressWarnings (" Unchecked ") public <T> t[] ToArray (t[] a) {if (A.length < size)//Make a new array of a
        ' s runtime type, but my Contents:return (t[]) arrays.copyof (elementdata, size, A.getclass ());
        System.arraycopy (elementdata, 0, a, 0, size);
        if (a.length > Size) a[size] = null;
    return A; //Positional Access Operations @SuppressWarnings ("unchecked") E elementdata (int index) {return (
    E) Elementdata[index];
     /** * Before obtaining a range check to see if the subscript is out of bounds * Returns the element at the specified position in this list.
     * * @param index of the element to return * @return The element at the specified position in this list

        * @throws indexoutofboundsexception {@inheritDoc} * */public E get (int index) {rangecheck (index); Return Elementdata (index); /** * Replaces the value on index and returns the old value * replaces the element at the specified position in this list with * the SPECIF
     IED element. 
     * @param index of the element to replace * @param element element to is stored at the specified position
     * @return The element previously at the specified position * @throws indexoutofboundsexception {@inheritDoc}

        */public E set (int index, E element) {Rangecheck (index);
        E OldValue = elementdata (index);
        Elementdata[index] = element;
    return oldValue;
     /** * Modcount * Appends the specified element to the end of this list when the expansion is available. * * @param e element to is appended to this list * @return <tt>true</tt> (as specified by {@link Col  Lection#add}) */public boolean Add (E e) {ensurecapacityinternal (size + 1);
        Increments modcount!!
        elementdata[size++] = e;
    return true; }

    /**
    * In the array copy of the Elementdata[index] and later elements are moved one position, that is, the original Elementdata[index] into the current element[index+1] * Inserts the SPECIF IED element at the specified position on this * list. Shifts the element currently at this position (if any) and * No subsequent elements to the right (adds one to their
     indices).
     * * @param index which the specified element is inserted * @param element element to be inserted * @throws indexoutofboundsexception {@inheritDoc} */public void Add (int index, E element) {Rangech

        Eckforadd (index);  Ensurecapacityinternal (size + 1);
        Increments modcount!!
        System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index);
        Elementdata[index] = element;
    size++;
    The/** *nummoved is the length that needs to be moved, assuming that index=0 is easily understood.
     * The deletion in the array is actually the implementation overlay, and then the last element is set to NULL, * and the deleted element * Removes is returned to the specified position in this list. * ShiFTS any subsequent elements to the left (subtracts one from their * indices).
     * * @param index The "the" is removed * @return the element that is removed from the list

        * @throws indexoutofboundsexception {@inheritDoc} */public E remove (int index) {rangecheck (index);
        modcount++;

        E OldValue = elementdata (index);
        int nummoved = size-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, index, n
        ummoved); Elementdata[--size] = null;
    Clear to let GC does its work return oldValue; /** * Removes the specified element that appears for the first time in this list, note that O overrides the Equals method * Removes the occurrence of the specified element from this LIS  T, * if it is present.  If The list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt> (o==null&nbsp;?  &nbsp;get (i) ==null&nbsp;:&nbsp;o.equals (get (i)) </tt> * (if such a element exists).
     Returns <tt>true</tt> If this list * contained the specified element (or equivalently, if this list * Changed as a result of

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.