Java Collection Class (1): ArrayList

Source: Internet
Author: User

Learn the collection classes of Java

(1) member variables and initialization

Private Static Final int Default_capacity = ten; Private Static Final object[] Empty_elementdata = {}; Private transient object[] Elementdata; Private int size;

The default size is 10.

Empty_elementdata is used for parameter-free initialization, an array of objects equal to null.

Elemendata is used for variables with parameter initialization, and is the principal object under which we operate.

Here's a look at the source code that is initialized:

 Public ArrayList (int  initialcapacity) {    Super();     if (initialcapacity < 0)         Throw New IllegalArgumentException ("Illegal capacity:" +                                            initialcapacity);      This New object[initialcapacity];}

An array of objects of size initialcapacity is initialized here

As can be seen from the initialization process: ArrayList is implemented based on dynamic arrays .

(2) Common operation

//API defined in collectionBooleanAdd (E object)BooleanAddAll (collection<?extendsE>collection)voidClear ()Booleancontains (Object object)BooleanContainsall (collection<?>collection)Booleanequals (Object object)inthashcode ()BooleanisEmpty () Iterator<E>iterator ()Booleanremove (Object object)BooleanRemoveAll (collection<?>collection)BooleanRetainall (collection<?>collection)intsize ()<T>t[] ToArray (t[] array) object[] ToArray ()//API defined in AbstractcollectionvoidAddintLocation , E object)BooleanAddAll (intLocation, collection<?extendsE>collection) E Get (intLocation )intindexOf (Object object)intlastIndexOf (Object object) Listiterator<E> Listiterator (intLocation ) Listiterator<E>listiterator () E Remove (intLocation ) E Set (intLocation , E object) List<E> sublist (intStartintend)//ArrayList the new APIObject Clone ()voidEnsurecapacity (intminimumcapacity)voidtrimtosize ()voidRemoveRange (intFromIndex,intToindex)

The Add method adds an element to the end of the current list
The AddRange method is used to add a batch of elements to the end of the current list
The Remove method is used to delete an element that is removed by a reference to the element itself
The RemoveAt method is used to delete an element by using the index value to remove
RemoveRange is used to delete a batch of elements by specifying the starting index and the number of deletions to delete
Inserts are used to add an element to the specified position, and the elements following the list move backward in turn
Insertrange is used to add a batch of elements starting at the specified position, and the elements behind the list move backwards

The clear method is used to clear all existing elements
The Contains method is used to find an object that is not in the list

Trimsize is used to pin the ArrayList to the actual element size, and when the dynamic array element is determined not to be added, this method can be called to free up free memory.
The ToArray method copy the elements of the ArrayList into a new array.

Here we special need to look at the source code of IndexOf:

 Public intindexOf (Object o) {if(O = =NULL) {         for(inti = 0; i < size; i++)            if(elementdata[i]==NULL)                returni; } Else {         for(inti = 0; i < size; i++)            if(O.equals (Elementdata[i]))returni; }    return-1;}
View Code

As can be seen here, IndexOf is implemented through a for loop, that is, to iterate through an array of objects, similar to the Contains method is to use a for loop to determine whether the element is included.

Therefore, the efficiency of such methods is extremely low, do not have to write their own for the loop to come fast, if you need to frequently use such fast key value lookup function, we recommend the use of HashMap.

(3) Dynamic adjustment of the size

from the Add () method, look at:

 public  boolean   add (e e) {ensurecapacityinternal (size  + 1); //     increments modcount!!     elementdata[size++] = E;  return  true  ;}
 Public void Add (int  Index, E Element) {    Rangecheckforadd (index);     + 1);  // increments modcount!!    System.arraycopy (Elementdata, index, Elementdata, index + 1,                        - index);     = element;    Size+ +;}
Add (int index, E Element)

The ensurecapacityinternal () function calls the Ensureexplicitcapacity () function and calls the Grow () function if it determines that expansion is required.

/*the maximum capacity. Some virtual machines may have several reserved information on the head of an array, so it is integer.max_value-8 if you want to create a arraylist that exceeds this limit, you will get an error: OutOfMemoryError*/Private Static Final intMax_array_size = integer.max_value-8;/*increase capacity to ensure that the minimum length requirement for all current elements can be accommodated. @param mincapacity The current minimum capacity requirement. */Private voidGrowintmincapacity) {    intOldcapacity =elementdata.length; intNewcapacity = oldcapacity + (oldcapacity >> 1); if(Newcapacity-mincapacity < 0) newcapacity=mincapacity; if(Newcapacity-max_array_size > 0) newcapacity=hugecapacity (mincapacity); Elementdata=arrays.copyof (Elementdata, newcapacity);}

The analysis of the most critical grow () function indicates:

Key:newcapacity = oldcapacity + (oldcapacity >> 1);

That newcapacity is 3 times times the size of oldcapacity.

Next check whether the size is reasonable, is less than the minimum bounds, greater than the maximum bounds (the maximum boundary definition has a minus 8 operation, is used to adapt to different virtual machine specifications, some virtual machines in the head of the array set aside several to store some relevant information)

Resize an array to return to Elementdata after resizing by copying the operation

(4) Traversal mode

The first, random access, gets the element through the index. The ArrayList implements the Randomaccess interface. Here is the get () method source code

 Public E get (int  index) {    Rangecheck (index);    Checkforcomodification ();     return ArrayList. this. Elementdata (offset + index);}

Second, for loop, take the integer element as an example

NULL ;  for (Integer integ:list) {    = integ;}

Third, iterate through the iterator (Iterator), taking the integer element as an example

Null= list.iterator ();  while (Iter.hasnext ()) {    = (Integer) Iter.next ();}

Of these three methods, the fastest access to random access, the slowest method of iterators

(5) serialization

ArrayList implements the Java.io.Serializable interface, can be serialized, the source code is as follows

/*** Save The state of the <tt>ArrayList</tt> instance to a stream (that* is, serialize it). * *@serialDatathe length of the array backing the <tt>arraylist</tt>* instance is emitted (int), followed B Y all it elements* (each a <tt>Object</tt>) in the proper order.*/Private voidWriteObject (java.io.ObjectOutputStream s)throwsjava.io.ioexception{//Write out element count, and any hidden stuff    intExpectedmodcount =Modcount;    S.defaultwriteobject (); //Write out size as capacity-behavioural compatibility with clone ()s.writeint (size); //Write elements in the proper order.     for(inti=0; i<size; i++) {s.writeobject (elementdata[i]); }    if(Modcount! =Expectedmodcount) {        Throw Newconcurrentmodificationexception (); }}/*** Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,* deserialize it).*/Private voidReadObject (java.io.ObjectInputStream s)throwsjava.io.IOException, classnotfoundexception {elementdata=Empty_elementdata; //Read in size, and any hidden stuffS.defaultreadobject (); //Read in capacityS.readint ();//ignored    if(Size > 0) {        //Be-like clone (), allocate array based upon size not capacityensurecapacityinternal (size); Object[] a=Elementdata; //Read in all elements in the proper order.         for(inti=0; i<size; i++) {A[i]=S.readobject (); }    }}
View Code

Java Collection Class (1): 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.