Java Collection framework: ArrayList

Source: Internet
Author: User

ArrayList definition
Package Java.util;public class Arraylist<e> extends abstractlist<e>        implements LIST<E> Randomaccess, cloneable, java.io.serializable{    private static final int default_capacity = ten;    private static final object[] Empty_elementdata = {};    Private transient object[] elementdata;    private int size;//Rest omitted}

  

ArrayList overview

  ArrayList is implemented as an array, allowing for repetition. Exceeding the limit increases the capacity by 50% (implemented in the Grow () method, as shown below), and each expansion is copied to the new array at the bottom with system.arraycopy (), so it is better to give a pre-estimate of the size of the group. The first time the element is inserted by default, the size of the array created is 10.

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);    }

Accessing elements by array subscript-get (i)/set (i,e) has a high performance, which is the basic advantage of arrays.

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;    }

has a high performance of adding elements-add (e) directly at the end of the array, but if you press the subscript insert, delete element-add (i,e), remove (i), remove (e), use System.arraycopy () to move partially affected elements , the performance becomes worse, which is a fundamental disadvantage.

 Public boolean Add (E e) {ensurecapacityinternal (size + 1);        Increments modcount!!        elementdata[size++] = e;    return true;        } 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++;        } 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, num        Moved); Elementdata[--size] = null;    Clear to let GC does its work return oldValue;                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; }

there is a method in ArrayList that TrimToSize () is used to reduce the size of the Elementdata array, which can save memory:

public void TrimToSize () {        modcount++;        if (Size < Elementdata.length) {            elementdata = arrays.copyof (elementdata, size);        }    }

Consider a situation where an application needs a ArrayList to expand to, say, size=10000, after a series of remove operations size=15, the ArrayList size remains within <100 for a long period of time, So it creates a lot of wasted space, it is recommended to explicitly call TrimToSize () This method to optimize memory space.
Or the capacity in a ArrayList is fixed, but since each expansion has been expanded by 50%, so there is a certain amount of space wasted, you can call TrimToSize () to eliminate these space waste.
  non-thread safe , you can call Collections.synchronizedlist (new arraylist<> ());

Use of ArrayList

To give a simple example:

list<integer> list = new arraylist<> ();        List.add (4);        List.add (2);        List.add (3);        List.add (5);        for (int i:list)        {            System.out.println (i);        }        SYSTEM.OUT.PRINTLN (list);

Operation Result:

4235[4, 2, 3, 5]

It is not surprising that ArrayList is stored in the order of insertion , and each insertion is inserted at elementdata[size++].

Use of sublist
list<integer> list = new arraylist<> ();        List.add (4);        List.add (2);        List.add (3);        List.add (5);        List.add (7);        List.add (5);        List.add (one);        List.add (+);        List.add (ten);        List.add (9);        SYSTEM.OUT.PRINTLN (list);        List<integer> List2 = list.sublist (3, 6);        System.out.println (LIST2);        List2.set (2, +);        System.out.println ("============");        SYSTEM.OUT.PRINTLN (list);        System.out.println (LIST2);

Operation Result:

[4, 2, 3, 5, 7, 5, 11, 14, 10, 9] [5, 7, 5]============[4, 2, 3, 5, 7, 50, 11, 14, 10, 9][5, 7, 50]

  

The difference between ArrayList and LinkedList
    1. ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on the linked list.
    2. For random access get and set,arraylist feel better than LinkedList because LinkedList wants to move the pointer.
    3. Add and remove,linkedlist are the dominant for new and deleted operations because ArrayList is moving the data.
The difference between ArrayList and vectors
    1. Vectors and ArrayList are almost identical, the only difference being that the vector is a synchronous class (synchronized), which belongs to the strong synchronization class. Therefore, the cost is larger than the ArrayList, and the visit is slower. Normally, most Java programmers use ArrayList instead of vectors, because synchronization can be controlled entirely by the programmer itself.
    2. Each time the vector expands it requests twice times its size, while the ArrayList is 1.5 times times.
    3. Vector also has a subclass stack.

Java Collection framework: ArrayList

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.