List---arraylist parsing of the Java collection

Source: Internet
Author: User

This chapter mainly describes the ArrayList collection of knowledge, mainly including ArrayList structure type, set characteristics, source code analysis and so On.

Welcome to continue to pay attention to reading, learning together, Common Exchange (477819525 June sheep).

1 ArrayList class Hierarchy:

650) this.width=650; "src=" http://img.blog.csdn.net/20170224154152480?watermark/2/text/ ahr0cdovl2jsb2cuy3nkbi5uzxqvamf2yv93zwvrbhk=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity/ Southeast "alt=" here to write a picture describing "title=" "style=" border:none;height:auto; "/>

2 ArrayList features:

A) ArrayList is an array-based implementation, is a dynamic array, can dynamically increase and decrease elements, the flexibility to set the size of the ARRAY.

B) ArrayList is not thread-safe, can only be used in a single-threaded environment, the multi-threaded environment may consider using the Collections.synchronizedlist (List l) function to return a thread-safe ArrayList class, You can also use the Copyonwritearraylist class under concurrent concurrent Packages.
Note: Concurrent Concurrency Toolkit related classes, will be in the article to do a specific explanation, this article does not repeat, if you want to know please consult related Articles.

C) each ArrayList instance has a capacity (the initial capacity defaults to 10). As you add elements to the arraylist, their capacity increases automatically.
Note: This implementation is not synchronous. If more than one thread accesses a ArrayList instance at the same time, and at least one of the threads modifies the list from the structure, it must remain externally synchronized.

D) for arraylist, It implements the list interface, and the underlying uses an array to hold all the Elements. Its operation is basically an array of operations.

E) Note the method of ensurecapacityinternal expansion Capacity. ArrayList calls this method to ensure sufficient capacity each time an element is added (perhaps 1 or a group). When the capacity is insufficient to accommodate the current number of elements, the new capacity is set to the right of the old capacity of one + old capacity, if the new capacity after the set is not enough, the direct new capacity is set to the incoming parameters (that is, the required capacity), and then use the Arrays.copyof () method to copy the elements to the new array. It can be seen that, when the capacity is not enough, each time the element is added, the original elements are copied to a new array, it is very time-consuming, it is recommended to determine the number of elements in advance to use arraylist, otherwise it is recommended to use Linkedlist.

F) the ArrayList is stable and disorderly. Stability (order) refers to the sequence of elements that each traversal of a set is Certain. Order (sort) means that the results of the traversal are sorted by some comparison Rule.

3 ArrayList source code Analysis (different JDK version of the source code structure differs, This article refers to jdk7):

A) ArrayList class
The ArrayList class implements the serializable interface, so it supports serialization, enables the Randomaccess interface (the interface does not define Anything) by serializing the transmission, supports fast random access, and in fact is quickly accessed by the subscript sequence Number. The Cloneable interface is implemented and can be Cloned.

public class Arraylist<e> extends abstractlist<e> implements list<e>, randomaccess, cloneable, ja Va.io.serializable{123123

B) Private Properties:
ArrayList defines only two private properties: Elementdata stores the elements within the arraylist, and the size represents the number of elements that it contains.

    private transient object[] elementdata;    /**      * The size of the ArrayList  (the number  Of elements it contains).      *     * @ serial     */    private int size;1234567812345678 

There is a key word to explain: Transient.
Java's serialization provides a mechanism for persisting object Instances. When persisting an object, there may be a special object data member, and we do not want to use the serialization mechanism to save it. In order to turn off serialization on a domain of a particular object, you can precede the field with the keyword Transient. (for example, to save the user object information, the user includes the Name,age,sex property information, if you do not want to save the age to the database, you can add the keyword transient, the attribute marked as transient will not be saved when the object is serialized).

C) Construction Method:
ArrayList provides a constructor of three ways, the first constructed method uses Initialcapacity to initialize the size of the Elementdata array, and the second constructs a null list with a default initial capacity of 10. The third construction method returns the provided Set-to-elementdata group (returned if not object[] will call the Arrays.copyof method to object[]).

    public arraylist (int initialcapacity)  {         super ();        if  (initialCapacity <  0)             throw new  IllegalArgumentException ("illegal capacity: " +                                                  initialcapacity);         this.elementdata = new  Object[initialCapacity];    }    /**      * constructs an empty list with an initial capacity of  ten.    &nbsP;*/    public arraylist ()  {         Super ();        this.elementdata = empty_elementdata;     }    /**     * constructs a list  containing the elements of the specified     *  Collection, in the order they are returned by the collection ' s      * iterator.     *     *   @param  c the collection whose elements are to be placed  into this list     *  @throws  nullpointerexception if  the specified collection is null     */     public arraylist (CoLlection<? extends e> c)  {         Elementdata = c.toarray ();        size =  elementdata.length;        // c.toarray might  ( Incorrectly)  not return Object[]  (see 6260652)          if  (elementdata.getclass ()  != object[].class)              elementdata = arrays.copyof (elementdata, size, object[ ].class);     } 1234567891011121314151617181920212223242526272829303112345678910111213141516171819202122232425262728293031

D) focus on the add (e) method:

Public boolean add (e e) {ensurecapacityinternal (size + 1);        Increments modcount!!        elementdata[size++] = e;    Return true; }1234512345

    private void ensurecapacityinternal (int mincapacity)  {         if  (elementdata == empty_elementdata)  {             mincapacity = math.max (DEFAULT_CAPACITY,  mincapacity);        }         ensureexplicitcapacity (mincapacity);     }    private void  ensureexplicitcapacity (int mincapacity)  {         modcount++;        // overflow-conscious code         if  (mincapacity - elementdata.length > 0)             grow (minCapacity);     }123456789101112131415123456789101112131415 

In the ensurecapacityinternal method, determine if the elementdata array is an empty array, and if it is empty, the maximum value between the initial capacity and the current size is given based on Max.max ().
In the Ensureexplicitcapacity method to modcount, Modcount is the number of times the list structure has been changed (each time the Ensureexplicitcapacity method is called, the value of Modcount will increase, But not necessarily the array structure will change, so the sense of modcount interpretation is not very in place). If the current size+1 is greater than the array capacity after the new element is added, the Grow method is Executed.

In the Grow method, the specific completion of the expansion implementation and the copy of the group, you can see the capacity expansion is the array capacity + array capacity Right shift one bit, basically equal to 1.5 times times the original Expansion. The limit of the array capacity is Integer.max_value.

    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);     }    private static int  hugecapacity (int mincapacity)  {        if  ( Mincapacity < 0)  // overflow             throw new outofmemoryerror ();         return  (mincapacity > max_array_size)  ?             Integer.MAX_VALUE :             max_array_size;    }1234567891011121314151617181912345678910111213141516171819

The array copy is done through the arrays.copyof () and system.arraycopy () methods.
First look at the arrays.copyof () method. It has a lot of overloaded methods, but the implementation of the idea is the same, we look at the generic version of the source code:

public static <T> t[] copyOf (t[] original, int newlength) {return (t[]) copyOf (original, newlength, Original    . GetClass ()); }123123

    public static <t,u> t[] copyof (U[] original, int  newlength, class<? extends t[]> newtype)  {         T[] copy =  ((object) newtype ==  (object) object[].class)              ?  (t[])  new Object[newLength]             :  (t[])  array.newinstance ( Newtype.getcomponenttype (),  newlength);         system.arraycopy ( original, 0, copy, 0,                          math.min (original.length,  newlength));         return copy;    } 1234567812345678

See System.arraycopy () method below.

    public static native void arraycopy (Object src,   int  srcpos,                                          Object dest, int destPos,                                           int length); 123123 

This method is labeled native, called the System's C + + code, is not visible in the jdk, but in the OPENJDK can see its source Code. The function actually eventually calls the C Language's memmove () function, so it can guarantee the correct copying and movement of elements within the same array, which is much more efficient than the general method of replication, and is well suited for batch processing of arrays. Java strongly recommends using this method when copying large numbers of array elements to achieve higher efficiency.


This article from the "java week a topic" blog, reproduced please contact the author!

List---arraylist parsing of the Java collection

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.