In-depth understanding of the---------ArrayList collection of the Java Collection framework

Source: Internet
Author: User
Tags throw exception

ArrayList Introduction

ArrayList is a dynamic array, using MSDN is a complex version of the array, it provides dynamic addition and reduction of elements, the implementation of the collection and list interface, you can flexibly set the size of the array, it is important to note that ArrayList is not thread-safe. Therefore, it is generally recommended to use the ArrayList array in a single thread

The inheritance relationship of ArrayList

  

public class Arraylist  extends  abstractlist<e>implement  list<e>,randomaccess,cloneable, Serializable

  

ArrayList method usage and source code parsing

① Construction Method

  

//1-----------------------public ArrayList () {this (10);    Call ArrayList (10) to initialize an object array of size 10 by default. }//2-------------------------public ArrayList (int initialcapacity) {if (initialcapacity < 0) thr         ow new IllegalArgumentException ("Illegal capacity:" + initialcapacity);                                              If the user initializes a size less than 0 throw exception, a new object array of user initial value size is created.    This.elementdata = new Object[initialcapacity];        }//3--------------------------public ArrayList (collection<? extends e> c) {elementdata = C.toarray ();        size = Elementdata.length;        The following conversions are made when C.toarray returns an array that is not of type object.    if (elementdata.getclass () = object[].class) Elementdata = arrays.copyof (elementdata, size, object[].class); }

The above three constructs indicate that using ArrayList by default produces an array of type object of size 10. You can also call ArrayList(int initialCapacity) to initialize the size of the object array. And the user can pass in a container to ArrayList as long as the container is of type collection. ArrayList(Collection<? extends E> c)when the interface is called, the container is serialized and the array value is assigned to the object array.

Instance:

  

public static void Main (string[] args) {        arraylist<integer> list_2=new arraylist<integer> (a);        List_2 add element for        (int i=0;i<10;i++)            list_2.add (i);        Arraylist<integer> list_3=new arraylist<integer> (list_2);        Output list_2 element for        (Integer a:list_2)            System.out.print (A + "");        Output list_3 element for        (Integer a:list_3)            System.out.print (A + "");    } Output/*list_2:0 1 2 3 4 5 6 7 8 9-----------------------list_3:0 1 2 3 4 5 6 7 8 9 *  

②indexof (Object o) method

Function: Find the position where an element first appears in ArrayList.

  

The element in public int indexOf (Object o) {  //arraylist can be null if NULL is returned if the subscript        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 (eleme Ntdata[i])                    return i;        }        If no corresponding element is found, return-1.        return-1;    }

A few notes to the IndexOf method: The ArrayList can hold a null element, IndexOf is the subscript that returns the first element of the same value in the Elementdata array, and the comparison method in IndexOf is equals and equals is the value of the comparison element. Therefore, you must find the null separately. Returns 1 if the element is not found.

Instance

  

public static void Main (string[] args) {        arraylist<integer> list=new arraylist<integer> ();        List.add (1);                List.add (2);                List.add (null);             List.add (2);        List.add (3);        SYSTEM.OUT.PRINTLN ("null:" +list.indexof (null));        System.out.println ("-------------------------");        System.out.println ("2:" +list.indexof (2));        System.out.println ("-------------------------");        System.out.println ("4:" +list.indexof (4));    }    Output/    *    null:2    -------------------------    2:1    -------------------------    4:1    */

③lastindexof (Object o) method

Function: Finds where an element last appears in ArrayList.

  

public int lastIndexOf (Object o) {        if (o = = null) {        ///If O is null from forward to the first null subscript for            (int i = size-1; I >= 0 ; i--)                if (elementdata[i]==null)                    return i;        } else {        //from behind to find the first subscript value O for            (int i = size-1; I >= 0; i -)                if (O.equals (Elementdata[i]))                    return i;        }        return-1;    }

The above code does a few things: LastIndexOf (Object O) finds the first subscript in the ArrayList with the same element as the value to look for, because it is lookup by value, so for NULL to find it separately. Returns 1 if not found

④get (int index) method

Function: Returns the element specified in ArrayList as index.

  

Public E get (int index) {//check whether the value of index is greater than the size of ArrayList        Rangecheck (index);//returns the element with index subscript               return Elementdata ( index);    }   e elementdata (int index) {        return (E) elementdata[index];    }   The value here checks the index >= size, because index<0 automatically throws an exception, so the index<0 is not checked. private void Rangecheck (int index) {        if (index >= size)            throw new Indexoutofboundsexception (Outofboundsmsg ( index));    }      

The above code to do a few notes: The above code only check the case of index>=size, in the case of Index<0 will also throw an exception, but this exception is thrown by the system. Index>=size the reason to check is that it is possible that the size of the array is larger than index, but the element that is valid <index does not throw an exception and returns an invalid value. For example, ArrayList has an initialization size of 10 and now puts 5 elements inside, and if index>=5, it should throw an exception instead of returning null. Because NULL can be actively placed in the ArrayList.

⑤set (int index, E Element) method

Function: The element is placed in the position labeled as index ArrayList, if Index<0 or Index>=size throws an exception, set (int index, E Element) can only overwrite the original elements in ArrayList. The returned value is the element that is overwritten.

  

1public e Set (int index, E Element) {//check if index is less than size, if not throw exception        Rangecheck (index);        E OldValue = elementdata (index);        Elementdata[index] = element;        Overrides the element on index in the ArrayList.        return oldValue;        Returns the element that is overwritten.    }//2     private void Rangecheck (int index) {        if (index >= size)            throw new Indexoutofboundsexception ( Outofboundsmsg (index));    }

⑥add (e-E) method
Function: Adds an element to the ArrayList.

  

/1-----------------------Public boolean add (E e) {ensurecapacityinternal (size + 1);        Check that the array's capacity is sufficient before adding elements elementdata[size++] = e;    return true;        }//2-----------------------private void ensurecapacityinternal (int mincapacity) {modcount++;    If the element is greater than the current length of the array, then the expansion if (Mincapacity-elementdata.length > 0) grow (mincapacity); }//3-----------------------private void Grow (int mincapacity) {//overflow-conscious code int oldcapacit        y = elementdata.length;        Increases the length of the array by half the original array.        int newcapacity = oldcapacity + (oldcapacity >> 1);            if (newcapacity-mincapacity < 0) newcapacity = mincapacity;        Newcapacity = mincapacity;mincapacity The number of actual elements if it is still not enough after half of the expansion.            if (newcapacity-max_array_size > 0) newcapacity = hugecapacity (mincapacity); Array maximum bit 2^32//mincapacity is usually close to size, so this is a win:elementdata = arrays.coPyof (Elementdata, newcapacity);      }

The Add method is more complex and involves expanding the array capacity. To find out the difference between size and elementdata.length, size refers to the number of elements stored in the array, elementdata.length represents the length of the array, and when new ArrayList system produces a elementdata array of length 10 by default, E lementdata.length=10, but because Elementdata has not put any elements in all size=0. If you add an element after the array size will be expanded first, each expansion will increase the size of the array by half, such as the size of the array size of 101 times after expansion of 10+5=10; The maximum length of the ArrayList is 2^32.

⑦add (int index, E Element) method
Function: add element to ArrayList specified index, add element and ArrayList size increases by 1. Index and subsequent elements will move backwards by one

  

//1-------------------------public void Add (int index, E element) {Rangecheck        Foradd (index);//Check whether the value of index is between 0 and size and can be a size.  Ensurecapacityinternal (size + 1);               See if the length of the elementdata is sufficient, not enough to expand//Elementdata the element from the back of index to a bit.        System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index);        Elementdata[index] = element;    size++;            }//2-------------------------private void Rangecheckforadd (int index) {if (Index > Size | | | Index < 0)    throw new Indexoutofboundsexception (Outofboundsmsg (index));        }//3-------------------------private void ensurecapacityinternal (int mincapacity) {modcount++;    Overflow-conscious code if (mincapacity-elementdata.length > 0) grow (mincapacity); }

Add (int index, E Element) adds an element to the specified index, checks the size of the array before adding the element, and if it is smaller then increases by half on the original basis, the ArrayList can only blame the index and the subsequent elements to move backward, Place the element at the index position.

⑧remove (int index) method
Function: Removes the element that arraylist the specified position.

  

Public E Remove (int index) {        Rangecheck (index);//If Index>=size throws an exception        modcount++;        E OldValue = elementdata (index);//Gets the value of the deleted element        int nummoved = size-index-1;        Move all elements behind the index one bit forward.        if (nummoved > 0)            System.arraycopy (Elementdata, index+1, Elementdata, index,                             nummoved);        Elementdata[--size] = null; Let GC does its work//returns the number of primitives to be deleted.        return oldValue;    }

⑨remove (Object o) method

Function: Delete element with value O in ArrayList

  

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

  

In-depth understanding of the---------ArrayList collection of the Java Collection framework

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.