Java Collection Source analysis: ArrayList source analysis

Source: Internet
Author: User
Tags addall arrays constructor contains empty int size serialization thread

ArrayList Introduction

ArrayList is based on the array, is a dynamic array, its capacity can automatically grow, similar to the C language Dynamic application memory, dynamic growth of memory.

ArrayList is not thread-safe and can only be used in a single-threaded environment, the collections.synchronizedlist (List L) function can be considered in a multithreaded environment to return a thread-safe ArrayList class. You can also use the Copyonwritearraylist class under the concurrent concurrency package.

ArrayList implements the serializable interface, so it supports serialization, can realize the Randomaccess interface through the serialization transmission, supports the fast random access, in fact is the fast access through the subscript serial number, realizes the Cloneable interface, can be cloned.

ArrayList Source Analysis

ArrayList's source code is as follows (added a more detailed note):

Package java.util; public class Arraylist<e> extends abstractlist<e> implements List<e>, Randomaccess, Cloneabl    
       
    E, java.io.Serializable {//serial version number private static final long serialversionuid = 8683452581122892189L;    
       
    ArrayList is based on the array implementation, using the array to save the data private transient object[] elementdata;    
       
    Number of actual data in ArrayList private int size;    
    ArrayList a constructor with capacity size.    
        Public ArrayList (int initialcapacity) {super ();    
                                               if (initialcapacity < 0) throw new illegalargumentexception ("illegal Capacity:" +    
        initialcapacity);    
    Creates a new array this.elementdata = new object[initialcapacity]; }//ArrayList parameterless constructor.    
    The default capacity is 10.    
    Public ArrayList () {this (10); //Create a ArrayList public ArrayList that contains Collection (Collection?    
        Extends e> c) {elementdata = C.toarray ();    
        size = Elementdata.length; if (Elementdata.getclass ()!= object[].class) Elementdata = arrays.copyof (elementdata, size, Object[].clas    
    s);    
        ///Set the current capacity value to the actual number of elements public void TrimToSize () {modcount++;    
        int oldcapacity = Elementdata.length;    
        if (Size < oldcapacity) {Elementdata = arrays.copyof (elementdata, size);    
    }//Determine the capacity of the arrarlist.  If the ArrayList capacity is insufficient to accommodate all current elements, set the new capacity = "(Original capacity x3)/2 + 1" public void ensurecapacity (int mincapacity) {//    
        Will "revise statistics" +1, this variable is mainly used to realize the fail-fast mechanism of the modcount++;    
        int oldcapacity = Elementdata.length; If the current capacity is insufficient to accommodate the current number of elements, set the new capacity = "(Original capacity x3)/2 + 1" if (Mincapacity > Oldcapacity) {Object Oldda    
            Ta[] = Elementdata; int newcapacity = (oldcapacity * 3)/2 + 1; If it is not enough, set the mincapacity directly to the current capacity if (Newcapacity < mincapacity) Newcapacity = Mincapaci    
            Ty    
        Elementdata = arrays.copyof (Elementdata, newcapacity); }///Add element E public boolean add (e e) {//Determine the capacity size of the ArrayList Ensurec  Apacity (size + 1);    
        Increments modcount!!    
        Add e to arraylist elementdata[size++] = e;    
    return true;    
    //Returns the actual size of ArrayList public int size () {return size; }//ArrayList contains Object (O) Public boolean contains (object o) {return indexOf (O) >    
    = 0;    
    }//Returns whether ArrayList is an empty public boolean isempty () {return size = = 0;  //forward lookup, return element's index value public int indexOf (Object o) {if (o = = null) {for (int i = 0; I &lT Size    
            i++) if (elementdata[i]==null) return i;    
                    else {for (int i = 0; i < size; i++) if (O.equals (elementdata[i)))    
            return i;    
        } return-1;    
            //Reverse lookup, return the index value of the element 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;    
            //Reverse lookup (lookup from end of array), return index value of Element (o) public int lastindexof (Object o) {if (o = = null) { for (int i = size-1 i >= 0; i--) if (elementdata[i]==null) return    
        Ielse {for (int i = size-1 i >= 0; i--) if (O.equals (elementdata[i))    
        return i;    
    } return-1; }//returns ArrayList Object array public object[] ToArray () {return arrays.copyof (E    
    Lementdata, size); //Returns an array of ArrayList elements public <T> t[] ToArray (t[] a) {//If the size of array a < ArrayList    
            Number of elements//A new t[] array, with an array size of "ArrayList elements" and copy "ArrayList" to the new array if (A.length < size)    
       
        Return (t[]) arrays.copyof (elementdata, size, A.getclass ());    
        If the size of the array a >= the number of ArrayList elements,//The entire elements of ArrayList are copied to array a.    
        System.arraycopy (elementdata, 0, a, 0, size);    
        if (a.length > Size) a[size] = null;    
    return A;    
  //Gets the element value of the index position public E get (int index) {rangecheck (index);     
        Return (E) Elementdata[index];    
       
        //Set the value of index position to element public E set (int index, e element) {Rangecheck (index);    
        E OldValue = (e) elementdata[index];    
        Elementdata[index] = element;    
    return oldValue;  ///Add E to ArrayList public boolean add (E e) {ensurecapacity (size + 1);    
        Increments modcount!!    
        elementdata[size++] = e;    
    return true; ///Add E to ArrayList at the specified location public void Add (int index, E element) {if (Index > Size | |    
       
        Index < 0) throw new Indexoutofboundsexception ("Index: +index+", Size: "+size);"  Ensurecapacity (size+1);    
        Increments modcount!!    
        System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index);    
        Elementdata[index] = element;    
    size++;  }  
       
    Delete ArrayList at the specified location//This column more highlights: http://www.bianceng.cn/Programming/Java/public E Remove (int index)    
       
        {Rangecheck (index);    
        modcount++;    
       
        E OldValue = (e) elementdata[index];    
        int nummoved = size-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, index, Nummo    
        VED); Elementdata[--size] = null;    
    Let GC does its work return oldValue;    
                }//delete arraylist specified element public boolean remove (Object o) {if (o = = null) {    
                for (int index = 0; index < size; index++) if (elementdata[index] = = null) {    
                Fastremove (index);    
            return true; } else {for (int index = 0; index < size; index++) if (o.equals) (Elementd    
         Ata[index])) {       Fastremove (index);    
            return true;    
    return false;    
        }//Quick delete index element private void Fastremove (int index) {modcount++;    
        int nummoved = size-index-1;    
        Starting with "index+1", replace the preceding element with the following elements.    
                             if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index,    
        nummoved); Set the last element to null elementdata[--size] = NULL; Let GC does its work}//Delete element public boolean remove (Object o) {if (o = = nul    
                L) {for (int index = 0; index < size; index++) if (elementdata[index] = null) {    
            Fastremove (index);    
            return true;    
            } else {//convenient ArrayList, find "element o", delete, and return true. for (int index = 0; index < size; index++) if (O.equals (Elementdata[index])) {fastremove (index);    
            return true;    
    return false;    
       
        }//Empty ArrayList, set all elements to null public void clear () {modcount++;    
       
        for (int i = 0; i < size; i++) elementdata[i] = null;    
    size = 0; ///Append collection C to ArrayList public boolean addall (collection<? extends e> c) {Object    
        [] A = C.toarray ();    
        int numnew = A.length;  Ensurecapacity (size + numnew);    
        Increments Modcount system.arraycopy (A, 0, elementdata, size, numnew);    
        Size + = Numnew;    
    return numnew!= 0;  ///starting at index position, add collection C to ArrayList public boolean addall (int index, COLLECTION&LT;? extends e> c) {if (Index > Size | | Index < 0) throw new inDexoutofboundsexception ("index:" + index + ", size:" + size);    
        Object[] A = C.toarray ();    
        int numnew = A.length;  Ensurecapacity (size + numnew);    
        increments modcount int nummoved = Size-index;    
                 if (nummoved > 0) system.arraycopy (elementdata, index, elementdata, index + numnew,    
       
        nummoved);    
        System.arraycopy (A, 0, Elementdata, index, numnew);    
        Size + = Numnew;    
    return numnew!= 0;    
    }//Delete all elements between Fromindex and Toindex.    
    protected void RemoveRange (int fromindex, int toindex) {modcount++;    
        int nummoved = Size-toindex;    
       
    System.arraycopy (Elementdata, Toindex, Elementdata, Fromindex, nummoved);    
    Let GC does its work int newsize = size-(TOINDEX-FROMINDEX); while (size!= newsize) elementdata[--sIZE] = null; private void Rangecheck (int index) {if (index >= size) throw new Indexoutofbound    
    Sexception ("Index:" +index+ ", Size:" +size);  ///Clone function Public Object clone () {try {arraylist<e> v =    
            (arraylist<e>) Super.clone ();    
            Copies all elements of the current ArrayList to v V.elementdata = arrays.copyof (elementdata, size);    
            V.modcount = 0;    
        return v;    
            catch (Clonenotsupportedexception e) {//This shouldn ' t happen, since we are cloneable    
        throw new Internalerror ();  }//Java.io.Serializable write function//writes the ArrayList "capacity, all element values" to the output stream private void WriteObject (Java.io.ObjectOutputStream s) throws java.io.ioexception{//Write out element count , and any hidden stuff int ExpectedmodcouNT = Modcount;    
       
        S.defaultwriteobject ();    
       
    Writes "The capacity of the array" S.writeint (elementdata.length);    
       
    Writes "Each element of the array" for (int i=0; i<size; i++) S.writeobject (elementdata[i));    
        if (Modcount!= expectedmodcount) {throw new concurrentmodificationexception (); }///java.io.Serializable Read function: Read/write according to writes/Read the ArrayList "capacity" and then "all element values "read out private void ReadObject (Java.io.ObjectInputStream s) throws Java.io.IOException, Classnotfoundexce    
       
        ption {//Read in size, and any hidden stuff s.defaultreadobject ();    
        Reads the ArrayList "capacity" int arraylength = S.readint () from the input stream;    
       
        Object[] A = Elementdata = new Object[arraylength];    
    Reads "All element values" from the input stream for (int i=0; i<size; i++) A[i] = S.readobject (); }    
}

Some summary

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.