One of the Java collection frameworks: ArrayList source analysis

Source: Internet
Author: User
Tags shallow copy

Copyright NOTICE: This article for Bo Master original article, reproduced please indicate the source, Welcome to exchange Study!

ArrayList the underlying maintenance is a dynamic array, each ArrayList instance has a capacity. This capacity refers to the size of the array used to store the list elements. It is always at least equal to the size of the list. As you add elements to the ArrayList, their capacity increases automatically.

ArrayList is not synchronous (that is, not thread-safe), and if multiple threads access a ArrayList instance at the same time, and at least one thread modifies the list from the structure, it must remain externally synchronized, in a multithreaded environment, You can use the Collections.synchronizedlist method to declare a thread-safe ArrayList, for example:

List arraylist = collections.synchronizedlist (New ArrayList ());

Below through the ArrayList source code to analyze its principle.

1, ArrayList construction method: ArrayList provides three different constructs the method

1) ArrayList (), constructs an empty list with an initial capacity of 10.

2) ArrayList (int initialcapacity), constructs an empty list with the specified initial capacity.

3) 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.

The source code is as follows:

  

  Private transient object[] elementdata;
  Public ArrayList (int initialcapacity) {super (); if (Initialcapacity < 0) throw new illegalargumentexception ("Illegal C Apacity: "+ initialcapacity); This.elementdata = new Object[initialcapacity]; Generates an array of type object of length 10    } public       ArrayList () {this (10);//Call ArrayList (int i)    }

Public ArrayList (collection<? extends e> c) { elementdata = C.toarray (); Returns an array containing all the elements in this collection size = Elementdata.length; C.toarray might (incorrectly) not return object[] (see 6260652) if (Elementdata.getclass ()! = Object[].class) Elementdat A = arrays.copyof (elementdata, size, object[].class); Copies the specified array, returning an array of type object containing the same element and length }

When building a collection object with a constructor without parameters ArrayList (), it is actually a construction method that calls ArrayList (int initialcapacity) at the bottom to produce an array of type object of length 10. When a construction method with a collection-type parameter is used, an array of type object containing the same element and length is generated at the bottom.

2. Add method: ArrayList provides two add methods for adding elements

1) Add (e E), adds the specified element to the end of this list.

2) Add (int index, e e), inserts the specified element into the specified position in this list. Move the element that is currently at that position (if any) and all subsequent elements (add 1) to the right and the private int size;

public boolean Add (E e) {ensurecapacity (size + 1);   Enlarge array capacity elementdata[size++] = e;    add element E to the object array labeled Size, and execute size++return true;  public void Add (int index, E element) {if (Index > Size | | Index < 0)//If the specified array to be inserted exceeds the array capacity or the specified subscript is less than 0, throw exception throw  New Indexoutofboundsexception ("Index:" +index+ ", Size:" +size); ensurecapacity (size+1);  Expands array capacity system.arraycopy (Elementdata, index, elementdata, index + 1,size-index); Copies an array from the specified source array, starting at the specified location and ending at the specified position in the destination array.  
//Elementdata---Source array index--- Start position in source array
//elementdata---Target Array index+1---Starting position in the target array
//size -Index---The number of array elements to copy elementdata[index] = element; Place the element you want to add to the specified array subscript at size++; }
public void ensurecapacity (int mincapacity) {Modcount++;int oldcapacity = elementdata.length;  The capacity of the original array if (Mincapacity > Oldcapacity) {    Object olddata[] = elementdata;    int newcapacity = (oldcapacity * 3)/2 + 1;  Defines the capacity of the new array, which is 1.5 times times the capacity of the original array +1        if (newcapacity < mincapacity) newcapacity = mincapacity;            Mincapacity is usually close to size, so this is a win:            Elementdata = arrays.copyof (Elementdata, newcapacity);  Copies the specified array, returning the new array's capacity to Newcapacity}    }

If there are more than 10 elements added to the collection, then the ArrayList layer will be reborn as an array, 1.5 times times the length of the original array, and the elements in the original array will be copied to the new array, and the subsequent additions are placed in the new array, and when the new array's length cannot accommodate the newly added element, Repeat the process. This is how the collection adds elements to the implementation.

3. Get method:

1) Get (int index), returns the element at the specified position in this list.

Public E get (int index) {rangecheck (index);//Check whether the incoming specified subscript is legal return (E) Elementdata[index];  Returns the array element labeled index in the array    }private void rangecheck (int index) {if (index >= size)  ///If the incoming subscript is greater than or equal to the capacity of the collection, throw an exception    throw new Indexoutofboundsexception ("Index:" +index+ ", Size:" +size);    }

  

4. Remove Method:

1) E Remove (int index) to remove the element at the specified position in this list. Move all subsequent elements to the left (index minus 1).

2) boolean remove (Object o) to remove the first occurrence of the specified element (if present) in this list. If the list does not contain this element, the list does not change and returns a Boolean value.

Public E Remove (int index) {rangecheck (index); Check whether the specified subscript is lawful modcount++;  E OldValue = (e) elementdata[index];  Gets the array element that specifies the subscript int nummoved = size-index-1;  The number of elements to move if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index, nummoved); Move array element elementdata[--size] = null;    Let GC does its workreturn oldValue; The public boolean remove (Object o) {if (o = = null) {///if the passed in parameter is NULL for (int index = 0; index < size; index++    if (elementdata[index] = = null) {//Remove the first occurrence of 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) {//Removes the element at the specified position, and implements the method like remove (int i) modcount++;        int nummoved = size-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, index, num        Moved); Elementdata[--size]= NULL; Let GC do it work}

 

5. Clone method:

1) Object clone (), which returns a shallow copy of this ArrayList instance (the elements themselves are not copied).

Public Object Clone () {try {    arraylist<e> v = (arraylist<e>) super.clone ();  The Clone method of the object class is called to return a ArrayList object    v.elementdata = arrays.copyof (elementdata, size);  Copy target array    v.modcount = 0;    return v;} catch (Clonenotsupportedexception e) {    //This shouldn ' t happen, since we is cloneable    throw new Internalerror (); }    }

  

The above through the ArrayList part of the key source of analysis, know the ArrayList bottom of the realization principle, about ArrayList source code has the following several points summary:

1) ArrayList The bottom layer is based on an array, you can find the target element accurately by subscript, so the efficiency of the search is high; but adding or removing elements involves moving a large number of elements, which is inefficient.

2) ArrayList provides three different construction methods, the parameterless construction method defaults to generating an array of type object of length 10, and when the number of elements added in the collection is greater than 10, the array is automatically expanded, i.e. a new array is generated and the elements of the original array are placed in the new array.

3) Ensurecapacity method to expand the array, it will generate a new arrays, the length of the original array of 1.5 times times +1, with the constant addition of elements to the ArrayList, when the length of the array is not enough to meet the need, repeat the process.

One of the Java collection frameworks: ArrayList source analysis

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.