Java collection of ArrayList source code parsing

Source: Internet
Author: User

Let's take a look at the underlying implementation of ArrayList,

ArrayList inherits the Abstractlist, realizes Cloneable, Serializable, randomaccess interface,

Its member properties are object[] elementdata and int size,

Obviously the bottom layer is to store elements in an extensible array,

New element

Like this code,

public static void Main (string[] args) {        list<integer> List = new arraylist<integer> ();        List.add (1);}

Let's go to the Add (e-E) method,

1 public boolean Add (E e) {2         ensurecapacityinternal (size + 1);  Increments modcount!! 3         elementdata[size++] = e;4         return true;5}

Size is a member property and is the base data type, so its initial value is 0,

Line 3rd elementdata[size++] = e; equivalent to first step first elementdata[0] = e, second step size self-increment,

The 2nd line of ensurecapacityinternal (size + 1), which we also mentioned, object[] Elementdata is an array that can be dynamically expanded,

Therefore, we need to verify that the current capacity is satisfied with the storage of the elements, if not satisfied, and how to do the expansion of the way?

Let's see ensurecapacityinternal (int mincapacity),

1 private void ensurecapacityinternal (int mincapacity) {2         if (elementdata = = Empty_elementdata) {3             mincapacity = Math.max (default_capacity, mincapacity); 4         }5 6         ensureexplicitcapacity (mincapacity); 7}

Default_capacity = 10 is the default array capacity,

Let's look at ensureexplicitcapacity (int mincapacity),

1 private void ensureexplicitcapacity (int mincapacity) {2         modcount++;3 4         //overflow-conscious CODE5         if ( Mincapacity-elementdata.length > 0) 6             grow (mincapacity); 7}

If the required length is greater than the current length of the array, grow (int mincapacity) is called.

1 private void Grow (int mincapacity) {2         //overflow-conscious code 3         int oldcapacity = elementdata.length; 4         int newcapacity = oldcapacity + (oldcapacity >> 1); 5         if (newcapacity-mincapacity < 0) 6             newcapacity = mincapacity; 7         if (Newcapacity-max_array_size > 0 ) 8             newcapacity = hugecapacity (mincapacity); 9         //mincapacity is usually close to size, so the is a win:10
   
    elementdata = arrays.copyof (Elementdata, newcapacity); 11}
   

The rule of expansion is that the length of the current array is multiplied by 1.5, and the result with decimals is an integer.

Finally call Arrays.copyof (t[] original, int newlength), directly see the implementation of the inner layer,

1 public static <T,U> t[] CopyOf (u[] original, int newlength, class<? extends T[]> NewType) {2         t[] copy = (object) NewType = = (object) object[].class) 3             ? (t[]) New object[newlength]4             : (t[]) array.newinstance (Newtype.getcomponenttype (), newlength); 5         System.arraycopy (original, 0, copy, 0,6                          math.min (original.length, Newlength)); 7         return copy;8}

Creates a new array and copies the contents of the original array into the new array.

Expansion Yes operation is int newcapacity = oldcapacity + (oldcapacity >> 1), we can think so

1. The expansion of the one-time too much, will inevitably result in excessive memory space consumption,

2. Too little expansion, will cause too many times, the next expansion will soon come, at the same time, the original array of elements copied into the new array, the frequent array copy needs to consume some performance,

So maybe it's a more eclectic approach,

Delete Element

The following code

1 public static void main (string[] args) {2         list<integer> List = new Arraylist<integer> (); 3         List.add (111); 4         List.add (222); 5         list.remove (1); 6         List.remove (222); 7}

The deletion of elements is divided into two types, one is to delete according to the subscript, and one is to delete by the element.

Follow the subscript to delete the element, first look at the code,

1 public E Remove (int index) {2         rangecheck (index); 3  4         modcount++; 5         E oldValue = elementdata (index); 6< c11/>7         int nummoved = size-index-1; 8         if (nummoved > 0) 9             system.arraycopy (Elementdata, index+1, ele Mentdata, index,10                              nummoved);         elementdata[--size] = null;//clear to let GC does its work12         return OLDV ALUE;14}

The second line, whether the checksum is out of bounds, the Nineth row after the deleted data element moves forward one bit, the 11th row size is reduced, and the last reference is pointed to null

Clear to let GC does its work!

Follow the elements to delete the elements, first look at the code,

public boolean remove (Object o) {        if (o = = null) {for            (int index = 0; index < size; index++)                if (ELEMENTDA Ta[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;}

After traversing to find the subscript call Fastremove (int index), the code is as follows,

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 let GC do it work}

The two implementations are almost the same, and the last is to invoke the move of the array element above and the last reference to let the virtual machine release the element itself.

inserting elements

The following section of code,

1 public static void main (string[] args) {2         list<integer> List = new Arraylist<integer> (); 3         List.add (111); 4         List.add (222); 5         List.add (1,22222); 6}

Line 5th indicates that 22222 is inserted after the first element,

We go to add (int index, E element),

1 public void Add (int index, E element) {2         rangecheckforadd (index); 3 4         ensurecapacityinternal (size + 1);  Increments modcount!! 5         system.arraycopy (elementdata, index, elementdata, index + 1,6                          size-index); 7         Elementdata[index] = Element;8         Size++;9}

Line 2nd, verify that the inserted position is within the size range of the array, otherwise run out of the exception,

Line 4th, determine whether the expansion is necessary, and the expansion of new elements is the same way,

Line 5th, insert the position to the last of all elements to move one bit backwards,

Line 6th, the reference to the inserted position points to the new element,

Below we ArrayList implemented the random interface, but Goose randomaccess is an empty interface, described in Javadoc,

Marker interface used by <tt>List</tt> implementations to indicate thatthey support fast (generally constant t IME) random access.

This is a markup interface, just a token, ArrayList implementation tag, indicating that it can quickly query the data,

From the above aspects, we summarize the advantages and disadvantages of ArrayList,

Advantages

1. Add a new element, order new, add a reference to the array element,

2. Array queries are fast,

Disadvantages

1. The deletion of elements, will cause the movement of some elements, will inevitably cause a certain effect of performance,

2. Inserting elements, which will cause the movement of some elements, will inevitably cause a certain effect of performance,

Therefore, in the business development, involves the query more, consider ArrayList.


Likewise, to draw on the great God's four points of focus for the collection

1. Whether to allow NULL,

2. Is the element allowed to repeat,

3. The order in which the elements are stored is consistent with the lookup order.

4. Is thread-safe,

ArrayList allows elements to be empty, allowing duplicates, orderly, non-thread-safe,

We'll look back at the definition of the array

Private transient object[] elementdata;

Modified by the transient keyword, which means that the array is not serialized, but rather provides writeobject (Java.io.ObjectOutputStream s), Javadoc has such a word,

Save the state of the <tt>ArrayList</tt> instance to a stream (Thatis, serialize it)

Let's take a look at WriteObject (Java.io.ObjectOutputStream s),

1 private void WriteObject (Java.io.ObjectOutputStream s) 2         throws java.io.ioexception{3         //Write out element cou NT, and any hidden stuff 4         int expectedmodcount = modcount; 5         s.defaultwriteobject (); 6  7         //Write out Siz  E as capacity for behavioural compatibility with clone () 8         s.writeint (size), 9/Write out all elements in the         Proper order.11 for         (int i=0; i<size; i++) {s.writeobject             (Elementdata[i]),         }14         if ( Modcount! = Expectedmodcount) {+             -throw new Concurrentmodificationexception ();         }18}

Line 5th, serialization of non-transient member properties,

On line 11th to 13th, there are elements in the array that are worth serializing individually.

The benefits of doing so,

1. Greatly shorten the time of serialization,

2. Reduce the size of the file after serialization.

Java collection of ArrayList source code parsing

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.