Brief analysis of Java ArrayList source code

Source: Internet
Author: User
Tags addall

Learn more things will find themselves more ignorant, recently read a variety of Daniel's blog and so on, deep feel their ignorance, waterfall sweat ... Put a positive attitude, slowly study, Hope Qinnengbuzhuo.


ArrayList is a relatively simple Java collection framework, learning data structure when a lot of people will choose to implement a similar function of the array of linear storage, in fact, ArrayList is the same, but its developers write more formal, below to see the source to see their ideas.

1. Definition

public class Arraylist<e> extends abstractlist<e>        implements List<e>, Randomaccess, Cloneable, Java.io.Serializable
from its definition see inherit from Abstractlist<e>, support generics,

Implementation of the list interface, the size of thelist interface variable array. All optional list operations are implemented and all elements, including null , are allowed. In addition to implementing the list interface, this class provides methods to manipulate the size of the array used internally to store the list. (This class is roughly equivalent to the Vector class, except that this class is not synchronized.) )

Randomaccess is a labeled interface, without any content,

Serializable indicates that it can be serialized, and no implementation of this interface can be serialized, and this interface is also a markup interface with no implementation.


★ Supplement: Serialization (serialization) is a process of describing an object in a sequence of bytes; Deserializing deserialization is a process of re-building these bytes into an object.

Use: a) when you want to save the object in memory in a file or in a database;
b) When you want to use sockets to transfer objects on the network;
c) When you want to transfer objects through RMI;

2. Field Summary

    /** * Default initial capacity.    */private static final int default_capacity = 10;     /** * Shared Empty array instance used for empty instances.    */private static final object[] Empty_elementdata = {}; /** * GKFX Empty array instance used for default sized empty instances.     We * Distinguish the empty_elementdata to know what much to inflate when * first element is added.    */private static final object[] Defaultcapacity_empty_elementdata = {};     /** * The array buffer into which the elements of the ArrayList is stored. * The capacity of the ArrayList is the length of this array buffer.  any * empty ArrayList with elementdata = = Defaultcapacity_empty_elementdata * 'll be a expanded to default_capacity     When the first element is added. */transient object[] elementdata; Non-private to simplify nested class access/** * The size of the ArrayList (the number of elements it contains)     .  * * @serial   */private int size; 
here Elementdata defined as transient, this key word explanation see: http://blog.csdn.net/luotuomianyang/article/details/51915759
In addition, a modcount is inherited from the abstractlist.

protected transient int Modcount
The number of times this list has been modified from the structure . Structural modification means changing the size of a list, or disrupting the list, so that an ongoing iteration produces an incorrect result.


3. Constructors


ArrayList()
Constructs an empty list with an initial capacity of 10.
ArrayList(Collection<? extends E> c)
Constructs a list of elements that contain the specified collection, arranged in the order in which they are returned by the collection iterator.
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.

    Public ArrayList () {this.elementdata = Defaultcapacity_empty_elementdata; }   /**     * Constructs an empty list with the specified initial Capacity. &nbs p;   *     * @param   initialcapacity  The initial capacity of the list & nbsp;   * @throws IllegalArgumentException If the specified initial capacity     * & nbsp;       is negative     */    public ArrayList (int initialcapacity) {        if (initialcapacity > 0) {             this.elementdata = new object[initialcapacity];        } else if (initialcapacity = = 0) {            this.elementData = empty_elementdata;       } else {            throw new IllegalArgumentException ("Illegal Capacity: "+ initialcapacity);       }   }   /* *     * Constructs a list containing the elements of the specified     * collectio         N, in the order they is returned by the collection ' s     * iterator. * Constructs a list of elements that contain the specified collection, in the order in which they are returned by the collection iterator      *     * @ Param c The collection whose elements is to being placed into this list     * @throws Nullpointerexcepti On if the specified collection are null     */    public ArrayList (collection<? Extends e> c) {        elementdata = C.toarray ();         if (size = elementdata.length)! = 0) {           //C.toarray might (incorrectly) not return object[] (see 6260652)   & nbsp;         if (Elementdata.getclass ()! = Object[].class)                  Elementdata = arrays.copyof ( Elementdata, size, object[].class);       } else {            //Replace with empty array.             This.elementdata = empty_elementdata;       }    }

4. Method Summary 4.1 Add

    Public boolean Add (E e) {        ensurecapacityinternal (size + 1);  Increments modcount!!        elementdata[size++] = e;        return true;    }

before adding new elements to determine whether the capacity is sufficient, not enough to expand, the method of expansion is as follows:

/**  * The maximum size of array to allocate.  * Some VMs Reserve Some headers words in a array.  * attempts to Allocat e larger arrays may result in  * outofmemoryerror:requested array size exceeds VM limit  */private static FINA  l int max_array_size = integer.max_value-8;        private void Grow (int mincapacity) {//overflow-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 close to size, so this is a win:elementdata = arrays.copyof (Elementdata, newcapacity); }
This method first calculates a capacity of Oldcapacity + (oldcapacity >> 1). That is, 1.5 times times the length of the Elementdata array. Again from Mincapacity andthis capacity takes a larger value as the size of the new array after expansion.

At this point, there are two situations:

A. The new capacity is less than the maximum value of the array max_array_size, i.e.

private static final int max_array_size = integer.max_value-8;

The largest capacity is set to integer.max_value-8, in the comments above the definition has been said, probably some JVM implementation, will put some extra data in front of the array, plus the size of the data in the array, it is possible to more than once to request the maximum size of the whole block of memory, Appears outofmemoryerror.


    public void Add (int index, E element) {        Rangecheckforadd (index);        Ensurecapacityinternal (size + 1);  Increments modcount!!        System.arraycopy (Elementdata, index, Elementdata, index + 1,                         size-index);        Elementdata[index] = element;        size++;    }
first determine whether the specified position index exceeds the bounds of the elementdata, and then call ensurecapacity to adjust the capacity (if sufficient capacity does not expand), Call system.arraycopy to copy the SIZE-INDEX elements elementdata from index to the index+1 to size+1 position (that is, the element starting with index moves backward one position). The value of the index position is then pointed to element.


    public boolean addall (collection<? extends e> c) {object[] a = C.toarray ();        int numnew = A.length;  Ensurecapacityinternal (size + numnew);        Increments Modcount system.arraycopy (A, 0, elementdata, size, numnew);        Size + = Numnew;    return numnew! = 0; }    public boolean addall (int index, COLLECTION&LT;? extends e> c) {     & nbsp;  Rangecheckforadd (Index);        object[] A = C.toArray ();         int numnew = a.length;        Ensurecapacityinternal (size + numnew); //increments modcount        int nummoved = size-index;        if (nummoved > 0)      & nbsp;      system.arraycopy (elementdata, index, elementdata, index + numnew,                               nummoved);        system.arraycopy (A, 0, Elementdata, index, numnew);        size + = numnew;         return numnew! = 0;   }
you can see that the method added is similar, judging whether the index is out of bounds, expanding, replicating.

4.2 Index

 Public Boolean contains (object o) {    return indexOf (o) >= 0;&nbsp,} 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)) Retu        RN I;    } return-1; } public int lastIndexOf (Object o) {     if (o = = null) {        F or (int i = size-1; I >= 0; i--)             if (Elementdata[i] ==null)               return i;      } else {         for (int i = size-1; I >= 0; i--)  &nbs p;           if (o.equals (elementdata[i)) &NBSP;&NBSP;&Nbsp;           return i;     }       return-1; }

By traversing the Elementdata array to determine whether the object is in the list, if present, returns index, or 1 if it does not exist. So the contains method can determine whether an object is contained in the list by the return value of the IndexOf (object) method. LastIndexOf is similar to the previous one, except that the for loop becomes a subsequent loop, starting with the last element.

4.3 Get and set

    Public E get (int index) {        Rangecheck (index);        Return Elementdata (index);    }

    Public E Set (int index, E element) {        Rangecheck (index);        E OldValue = elementdata (index);        Elementdata[index] = element;        return oldValue;    }
where Rangecheck is an indexed range of checks

    private void Rangecheck (int index) {        if (index >= size)            throw new Indexoutofboundsexception (Outofboundsmsg ( index));    }
The whole realization of fried chicken simple has wood there!

4.4 Removal

Removes the element at the specified position in this list.

    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,                             nummoved);        Elementdata[--size] = null; Clear to let GC does its work        return oldValue;    }
removes the specified element (if any) that first appears in this list.

    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 (Elementdata[index])                    ) {Fastremove (index);                return true;    }} return false; }    private void Fastremove (int index) {        modcount++;         int nummoved = size-index-1;        if ( nummoved > 0)             system.arraycopy (Elementdata, Index+1, Elementdata, Index, nummoved);        elementdata[--size] = null; Clear to allow GC do it work for easy garbage collection &NBSP;&NBsp; } 

Removes all elements in the list between FromIndex (inclusive) and Toindex (not included).
    protected void RemoveRange (int fromIndex, int toindex) {        modcount++;        int nummoved = Size-toindex;        System.arraycopy (Elementdata, Toindex, Elementdata, FromIndex,                         nummoved);        Clear to let GC does its work        int newSize = size-(toindex-fromindex);        for (int i = newSize; i < size; i++) {            elementdata[i] = null;        }        size = newSize;    }
removes all elements in the list between FromIndex(inclusive) and Toindex(not included). Moves all subsequent elements to the left (decreasing their index). This call shortens the list of (Toindex-fromindex) elements. (If toindex==fromindex, this operation is not valid.) )

4.5 TrimToSize ()

    public void TrimToSize () {        modcount++;        if (Size < Elementdata.length) {            Elementdata = (size = = 0)              ? Empty_elementdata              : arrays.copyof (elementdata, size);        }    }
since the length of the Elementdata is extended, the size tag is the number of elements contained therein. So there will be a small size but elementdata.length a large situation, there will be wasted space. TrimToSize will return a new array to Elementdata, the element content remains unchanged, length is the same size, saving space.

Three-mesh operators:

X? Y:ZX is a Boolean type, and if X is true, the result shows Y, and if X is false, the result is Z.

Brief analysis of Java ArrayList source code

Related Article

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.