JAVA ArrayList Structure Analysis

Source: Internet
Author: User

/**   2       * The array buffer into which the elements of the ArrayList is stored.  3 * The capacity of the ArrayList is the length of this       array buffer.  4       */   5      privatetransient  object[] elementdata   ; 6     7      /**8 * The size of the ArrayList (the number of       elements it contains).  9       *       @serial  * *       /       Private  int size;  

As we can see from here, ArrayList is implemented with an array, including the elementdata arrays and their size two properties.

1  Public Boolean Add (e e) {  2     ensurecapacity (size + 1);  // increments modcount!!   3     elementdata[size++] = e;   4     return true ;   5 }  
/*** Increases the capacity of this <tt>ArrayList</tt> instance, if * necessary, to ensure that       It can hold at least the number of elements * specified by the minimum capacity argument. *       * @parammincapacity the desired minimum capacity*/        Public voidEnsurecapacity (intmincapacity) {Modcount++; intOldcapacity =elementdata.length; if(Mincapacity >oldcapacity) {Object olddata[]=Elementdata; intNewcapacity = (oldcapacity * 3)/2 + 1; if(Newcapacity <mincapacity) newcapacity=mincapacity; //mincapacity is usually close to size, so this is a win:Elementdata =arrays.copyof (Elementdata, newcapacity); }       }  

Ensurecapacity ensure that the inner array size satisfy the Add (Object o) operation. If mincapacity is bigger than the original array size, it increase the array size and do the checking again. Ensurecapacity () would increase the array size by at least 1. After the array of size is OK, copy original array to new array with bigger size. After Ensurecapacity () was returned, set elementdata[size] to be the newly added element. Since the array size is increased by at least one. Call Elementdata[size] would not throw exception.

JAVA ArrayList Structure 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.