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.
ArrayList inherits from the list interface and provides methods to manipulate the size of the array used internally to store the list, in addition to the inherited methods.
Each ArrayList instance has a capacity. This capacity refers to the size of the array used to store the list elements. It is always at least equal to the size of the list. As you add elements to the ArrayList, their capacity increases automatically. The details of the growth strategy are not specified, as it is not just the addition of elements that can be as simple as allocating fixed-time overhead.
ArrayList are often used, and in general, when used, they are declared like this:
List arrayList = new ArrayList ();
If you use the default construction method as above, the initial capacity is set to 10. When there are more than 10 elements in the ArrayList, the memory space is redistributed, and the size of the array is increased to 16.
You can see the number of dynamic growth changes by debugging: 10->16->25->38->58->88->
You can also declare it in the following way:
List arrayList = new ArrayList (4);
Set the default capacity of ArrayList to 4. When there are more than 4 elements in the ArrayList, the memory space is redistributed, and the size of the array is increased to 7.
You can see the number of dynamic growth changes by debugging: 4->7->11->17->26->
So what are the rules for capacity change? Take a look at the following formula:
(Old capacity * 3)/2) + 1
Note: This is different from the C # language, and the algorithm in C # is simple and doubles.
Once the capacity changes, there is additional memory overhead, and time overhead.
Therefore, in cases where the capacity is already known, it is recommended to declare it in the following way:
List arrayList = new ArrayList (capacity_size);
That is, the way to specify the default capacity size.
explore ArrayList automatically change the size of the truth ArrayList the list object is essentially stored in a reference array, some people think that the array has an "auto-growth mechanism" can automatically change size. Formally, the array cannot be resized, in fact it simply changes the point of the reference array. Now, let's look at how Java implements the ArrayList class. The real ArrayList of the ArrayList class is implemented by an array of type object, and when a ArrayList object is generated using a constructor without parameters, an array of type object of length 10 is actually generated at the bottom. First, ArrayList defines a private, non-serialized array elementdata, which is used to store the ArrayList list of objects (note that definitions are not initialized):Private transientobject[] Elementdata; Next, instantiate the Elementdata array after specifying the initial capacity (capacity) or converting the specified collection to a reference array, or, if not specified, the initial capacity of 10 for instantiation. Pre-instantiating a private array, and then overwriting the original array through the Copyof method, is the key to implementing an automatic change in the size of the ArrayList (size). Some people say that ArrayList is a complex array, and I think it's better to say ArrayList is a combination of methods about arrays of systems. ArrayList construction method source code is as follows://constructs an empty list with the specified initial capacity. PublicArrayList (intinitialcapacity) { Super(); if(Initialcapacity < 0) Throw NewIllegalArgumentException ("Illegal capacity:" +initialcapacity); This. Elementdata =NewObject[initialcapacity];//property to the new temporary array with the original length of the initial capacity } //constructs an empty list with initial capacity 10 PublicArrayList () { This(10); } / *constructs a list of specified collection elements returned sequentially by iterators that utilize collection*@param the C collection, its elements are used to put the list T* @throwsNullPointerException if the specified collection isNULL*/ PublicArrayList (collection<?extendsE>c) {Elementdata= C.toarray ();//initialize an array with collection ElementdataSize =elementdata.length; if(Elementdata.getclass ()! = object[].class) Elementdata= arrays.copyof (elementdata, size, object[].class); ArrayList implementation automatically changes the size mechanism in order to implement this mechanism, Java introduces the concept of capacity and size to distinguish the length of the array. To ensure that the user adds a new list object, Java sets the minimum capacity (mincapacity), which is usually larger than the number of list objects, so capactiy is the length of the underlying array, but it is meaningless for the end user. A size that stores the number of list objects is what the end user needs. To prevent user error modification, this property is set to Privae, but can be obtained through size (). The following is an analysis of the size auto-change mechanism in three cases, such as the initial ArrayList and the addition and deletion of its list objects. 1, initial capacity, and size values. From the source of the ArrayList construction method given above, it is not difficult to see that the capacity initial value (initialcapacity) can be determined by the number of objects directly specified by the user or stored by the collection collection specified by the user, and if not specified, the system defaults to 10. While the size is declared as an int variable, the default is 0, and when the user specifies collection to create ArrayList, the size value equals initialcapacity. 2, Add () method The source code for this method is as follows: Public BooleanAdd (e e) {ensurecapacityinternal (size+ 1); Elementdata[size+ +] = e;//self-increment size when adding objects return true; The ensurecapacityinternal called in the method is used primarily to adjust the capacity and to modify the Elementdata array's direction. This involves the invocation of 3 methods, the core of which is the Grow method:Private voidEnsurecapacityinternal (intmincapacity) {Modcount++;//parent class Abstractlist defined in ArrayList, used to store structure modification times//overflow-conscious Code if(Mincapacity-elementdata.length > 0) grow (mincapacity); } Private voidGrowintmincapacity) { //overflow-conscious Code intOldcapacity =elementdata.length; intNewcapacity = oldcapacity + (oldcapacity >> 1);//The new capacity expands to 1.5 times times the original capacity, and the right shift one is related to the original value divided by 2. 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); } Private Static intHugecapacity (intmincapacity) { if(Mincapacity < 0)//Overflow Throw NewOutOfMemoryError (); return(Mincapacity > Max_array_size)?Integer.MAX_VALUE:MAX_ARRAY_SIZE;//Max_array_size and Integer.max_value are constants, see note below for detailsthrough the above code, we know that Java automatically increase the ArrayList size of the idea is: Add objects to ArrayList, the number of original objects plus 1 if the original array is greater than the length of the underlying array, the appropriate length to create a copy of the original, and modify the original array, point to the new array. The original array is automatically discarded (the Java garbage collection mechanism is automatically recycled). Size adds an object to the array, increasing by 1. NOTES://a constant defined in the class that is used to allocate the size of the array to the maximum value. Some VMS retain the word header in the array, and attempting to allocate a larger array may cause OutOfMemoryError: The array of the requestedsize exceeds VM bounds. Private Static Final intMax_array_size = integer.max_value-8; //in the Java.lang.Integer class, the constants Min_value, Max_value are as follows: Public Static Final intMin_value = 0x80000000;//integer-value interval lower bound: -2147483648 Public Static Final intMax_value = 0x7fffffff;//upper bound of integer value interval: 2147483647//in Java.util.AbstractList, Modcount is defined as follows: protected transient intModcount = 0; 3, remove () method One of the following is the source code (the other is not exhausted): 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);//move the following list object forwardElementdata[--size] =NULL;//The array moves forward one bit, the size is reduced, the empty position is null, and the specific object is destroyed by the junk collector . returnOldValue; } Private voidRangecheck (intIndex) {//boundary Check if(Index < 0 | | | Index >= This. Size)Throw Newindexoutofboundsexception (outofboundsmsg (index)); } E Elementdata (intIndex) {//gets the object that specifies the position of index return(E) Elementdata[index]; Through the study of the Remove () source code, it is not difficult to see that its change ArrayList size of the core and the Add () method is similar to the same array copy. In addition, if necessary, the user can also specify the capacity of the ArrayList instance, which can effectively reduce the time cost. It is implemented by calling Ensurecapacityinternal, with the following source code: Public voidEnsurecapacity (intmincapacity) { if(Mincapacity > 0) ensurecapacityinternal (mincapacity); Because the size is private, Java gives the method to access it: Public intsize () {checkforcomodification (); return This. Size; In summary, when the user appends an object to ArrayList, Java always calculates the appropriate capacity (capacity), and copies the original array to a new array created with the specified capacity for a length of time, and assigns the original array variable to the new array if the capacity is insufficient. At the same time, the size is self-increment by 1. When deleting an object, first use the Copy method to move the object after the specified index 1 bits (if any), and then place the vacated position null, to the junk collector to destroy, size from minus 1, that is done.
Initial capacity and capacity allocation for ArrayList in Java