Analysis of ArrayList source code of Java class set framework

Source: Internet
Author: User
Tags addall


ArrayList

An array-based implementation is essentially a variable-length array of object references that can dynamically increase or decrease its size.

is not thread-safe and can only be used in a single-threaded environment. You can consider using the Collection.synchronizedlist (List L) function to return a thread-safe ArrayList class in a multithreaded environment, or you can use the concurrent concurrent package

Copyonwritearraylist class

The following directly paste ArrayList Java implementation, source Jdk1.8.0_25/src.zip.

public class Arraylist<e> extends abstractlist<e> implements List<e>, Randomaccess, Cloneable, JAVA.IO.SERIALIZABLE{//implements the Randomaccess interface, supports fast random access//implementation of Cloneable interface, can be cloned//implements the Serializable interface, supports serialization of private static Final long serialversionuid = 8683452581122892189l;//sequence version number private static final int default_capacity = 10;//default initial capacity pri vate static final object[] Empty_elementdata = {};//empty array private static final object[] Defaultcapacity_empty_elementdata = {};//default empty array transient object[] elementdata;//not serialized private int size;//arraylist actual element capacity//constructor 1---Capacity-size constructors Pub LIC ArrayList (int initialcapacity) {if (initialcapacity > 0) {this.elementdata = new Object[initialca       pacity];//specifies the size array} else if (initialcapacity = = 0) {this.elementdata = Empty_elementdata; } else {throw new illegalargumentexception ("Illegal capacity:" + I       nitialcapacity); }}//constructor 2---No parameter constructor, no specifiedWhen size, the default construction size is 10 for the array public ArrayList () {this.elementdata = Defaultcapacity_empty_elementdata;        }//Constructor 3---Constructs a list containing the specified Collection elements, which are public ArrayList (COLLECTION&LT; extends e> c) that are returned in their order by Collection Iterators; {       Elementdata = C.toarray ();       if (size = elementdata.length)! = 0) {//C.toarray might (incorrectly) not return object[] (see 6260652) http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6260652 can view the bug library if (Elementdata.getclass ()! = object[].       Class) Elementdata = Arrays.copyof (elementdata, size, object[].class);           } else {//Replace with empty array.       This.elementdata = Empty_elementdata; }}//Set the current capacity to actual capacity public void TrimToSize () {modcount++;//fast-fail mechanism, accessed if modifying the collection throws Concurrentmodificationexcep tion exception if (size < elementdata.length) {Elementdata = (size = = 0)?       EMPTY_ELEMENTDATA:Arrays.copyOf (elementdata, size); }}//Increase capacity to mincapacity pubLIC void ensurecapacity (int mincapacity) {int minexpand = (elementdata! = defaultcapacity_empty_elementdata)? 0:DEFA            ult_capacity;       if (Mincapacity > Minexpand) {ensureexplicitcapacity (mincapacity);  }} private void ensurecapacityinternal (int mincapacity) {if (Elementdata = = Defaultcapacity_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); } private static final int max_array_size = integer.max_value-8;//can allocate a maximum capacity//each time the memory is redistributed, the new capacity is 1.5 times times the old///But if the allocation after more than can The allocated memory range is allocated integer.max_value size, then the maximum size of the allocated capacity is compared, if it is greater than the allocation integer.max_value, if it is less than the allocated max capacity, the private void grow (int       mincapacity) {//overflow-conscious code int oldcapacity = elementdata.length;int newcapacity = oldcapacity + (oldcapacity >> 1);//Set new capacity = raw capacity *1.5 if (newcapacity-mincapacity < 0)//       The increased capacity is not enough 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 Outo       Fmemoryerror ();           Return (Mincapacity > Max_array_size)?   Integer.MAX_VALUE:MAX_ARRAY_SIZE;   } public int size () {return size;   }//Is empty public boolean isEmpty () {return size = = 0;   }//Whether to include the specified element o public boolean contains (Object o) {return indexOf (O) >= 0; }//Returns the specified element position, if no 1 is returned, the element to find is allowed to be null public int indexOf (Object o) {if (o = = null) {for (int i = 0; I &l T Size i++) if (ELEMENTDATa[i]==null) return i; } else {for (int i = 0; i < size; i++) if (O.equals (Elementdata[i])) return       I   } return-1; }//Returns the last occurrence, if not returned-1 public int lastIndexOf (Object o) {if (o = = null) {for (int i = size-1; ; = 0;       i--)//Look forward to the IF (elementdata[i]==null) return i; } else {for (int i = size-1; I >= 0; i--) if (O.equals (Elementdata[i])) Retu       RN I;   } return-1;           }//Clone function Public Object clone () {try {arraylist<?> v = (arraylist<?>) super.clone ();           V.elementdata = arrays.copyof (elementdata, size);           V.modcount = 0;       return v; } catch (Clonenotsupportedexception e) {//This shouldn ' t happen, since we is cloneable throw new in       Ternalerror (e); }} public object[] ToArray () {return ARRAYS.COpyof (elementdata, size);  } @SuppressWarnings ("Unchecked") public <T> t[] ToArray (t[] a) {if (A.length < size)//Make       A new array of a ' s runtime type, but my Contents:return (t[]) arrays.copyof (elementdata, size, A.getclass ());       System.arraycopy (elementdata, 0, a, 0, size);       if (a.length > Size) a[size] = null;   return A; }//Positional Access Operations @SuppressWarnings ("unchecked") E elementdata (int index) {return (E) element   Data[index];    }/** * Returns the element at the specified position in this list. * * @param index Index of the element to return * @return The element at the specified position in this list * @       Throws Indexoutofboundsexception {@inheritDoc} */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;  } public boolean Add (E e) {ensurecapacityinternal (size + 1);       Increments modcount!!       elementdata[size++] = e;   return true;     }//adds an element to the specified position, the original position element does not disappear, but moves back one bit, moving the element that is currently in that position and all subsequent elements to the right one position.       public void Add (int index, E element) {Rangecheckforadd (index);  Ensurecapacityinternal (size + 1);       Increments modcount!! Copy the elements from the index position in the Elementdata, which are size-index in length, to the new Elementdata array starting from the index+1 position system.arraycopy (Elementdata,       Index, Elementdata, index + 1, size-index);       Elementdata[index] = element;   size++;       }//Removes the specified position element, after which all elements move forward one 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,nummoved); Elementdata[--size] = null; Clear to let GC do it work return OLDVAlue; }//Removes the first occurrence of the specified element if it does not exist returns false public boolean remove (Object o) {if (o = = null) {if (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;       } private void Fastremove (int index) {modcount++;       int nummoved = size-index-1; if (nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, index, Nummo       VED); Elementdata[--size] = null;       Clear to let GC do it work} public void Clear () {modcount++;       Clear to let GC does its work for (int i = 0; i < size; i++) elementdata[i] = null;   size = 0; } PUBlic boolean addall (collection<? extends e> c) {object[] a = C.toarray ();       int numnew = A.length;  Ensurecapacityinternal (size + numnew);       Increments Modcount system.arraycopy (A, 0, elementdata, size, numnew);       Size + = Numnew;   return numnew! = 0;       } public boolean AddAll (int index, COLLECTION&LT;? extends e> c) {rangecheckforadd (index);       Object[] A = C.toarray ();       int numnew = A.length;  Ensurecapacityinternal (size + numnew);       increments modcount int nummoved = Size-index;                            if (nummoved > 0) system.arraycopy (elementdata, index, elementdata, index + numnew,       nummoved);       System.arraycopy (A, 0, Elementdata, index, numnew);       Size + = Numnew;   return numnew! = 0;       } protected void RemoveRange (int fromIndex, int toindex) {modcount++;       int nummoved = Size-toindex;       System.arraycopy (Elementdata, Toindex, Elementdata, FromIndex,                 nummoved);       Clear to let GC does its work int newSize = size-(TOINDEX-FROMINDEX);       for (int i = newSize; i < size; i++) {elementdata[i] = null;   } size = NewSize; }

Construction Method:

There are 3 ways to construct ArrayList, parameters can specify capacity size, can be empty (a null array with a default size of 10 is constructed), or an array can be initialized by an element in collection C.

Capacity Growth method:

The capacity growth method for ArrayList can be seen in grow (). ArrayList each time an element is added, the method is called indirectly to ensure capacity. Assignable maximum capacity is max_array_size = Integer.max_value-8

However, the actual maximum allocated capacity may be integer.max_value.

In the process of adding elements, if the current capacity is not sufficient to accommodate the element, it is set to a new capacity of about 1.5 times times the old capacity, the previous version is

The methods used by JDK1.8 are:

Newcapacity = oldcapacity + (oldcapacity >> 1);
The main shift operation is faster than multiplication division.

If the new capacity after expansion is still insufficient, set the new capacity directly to the incoming parameter (mincapacity). If the new capacity after expansion than the maximum allowable capacity max_array_size = Integer.max_value-8 also larger, then regardless of full requirements, set the capacity of integer.max_value, which is said to allow the maximum allocation capacity of MAX_ Array_size, but the actual maximum allocation capacity may be the reason for Integer.max_value. Of course, the minimum allocated capacity is the default capacity of 10, even if the specified allocation capacity is less than 10, the capacity is allocated 10,

Description

When looking for an element, you can find the index of a null element, as you can see from the source, when you look for an element, it is distinguished by null and non-null.

It must be noted that, after the expansion, but also to copy the original elements into a new array, it is very time-consuming, it is recommended to know the number of elements in advance to use ArrayList, otherwise it is recommended to use LinkedList

ArrayList is based on an array implementation, it is possible to find the element at the specified location directly through the subscript index, so the lookup is efficient, but in the process of inserting and deleting elements, it is inefficient to move the elements a lot.





Analysis of ArrayList source code of Java class set 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.