/** 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