The implementation of a variable array of size for the List interface. All optional list operations are implemented and all elements, including null , are allowed. In addition to implementing the list interface, this class provides methods to manipulate the size of the array used internally to store the list. (This class is roughly equivalent to the Vector class, except that this class is not synchronized.) )
Each ArrayList instance has a capacity, and the default length is the object that 10,arraylist will add, essentially
is stored in the object array, and when the number of objects is saved enough to reach the maximum value of the container length, the ArrayList
will be expanded by 1/2 of the current array length for each expansion size, and the saved element can be a null value and can be duplicated.
Main Features:
1. Do not guarantee that the container has enough space to save the elements, do not waste memory space, each time you add elements to confirm whether the length
Sufficient, if the capacity limit is reached, expansion will be carried out.
Private voidGrowintmincapacity) { //overflow-conscious Code intOldcapacity =elementdata.length; intNewcapacity = oldcapacity + (oldcapacity >> 1); if(Newcapacity-mincapacity < 0) 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); }
View Code
2. In order to implement a quick query, the element is counted inside the class through the property size
/** * The size of the ArrayList (the number of elements it contains). * @serial*/ privateint size;
View Code
Public Boolean Add (e e) { + 1); // increments modcount!! elementdata[size++] = e; return true ; }
View Code
3. When you delete an element, all other elements that are at the index of the element at the time of deletion move to the left and have a certain effect on performance
/*** Removes the element at the specified position of this list. * Shifts Any subsequent elements to the left (subtracts one from their * indices). * * @paramIndex the index of the element to be removed *@returnThe element that is removed from the list *@throwsindexoutofboundsexception {@inheritDoc} */ PublicE Remove (intindex) {Rangecheck (index); Modcount++; E OldValue=Elementdata (index); intnummoved = size-index-1; if(nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index, nummoved); elementdata[--size] =NULL;//clear to let GC do it work returnOldValue; }
View Code
4. The element substitution operation is to specify the index location, modify the memory address that the current index position variable points to, and not cause a change in location, so performance is no problem.
Public E set (int index, e Element) { Rangecheck (index); = Elementdata (index); = element; return oldValue; }
View Code
Variable group set ArrayList