ArrayList inherits from the Abstractlist abstract class and implements the list interface.
public class Arraylist<e> extends abstractlist<e> implements List<e>, randomaccess, cloneable, ja Va.io.Serializable
An array of type object is used to store data in the ArrayList class
Private transient object[] elementdata;
The elementdata here is decorated with the transient keyword. Variables modified by the Transient keyword are not manipulated when the object is serialized. When the ArrayList object is serialized, is the elementdata array really not handled? Let's look at the WriteObject function:
S.defaultwriteobject ();//write out array lengths.writeint (elementdata.length);//write out all elements in the proper Ord er.for (int i=0; i<size; i++) S.writeobject (Elementdata[i]);
In fact, Elementdata is artificially serialized.
When instantiating a ArrayList object, the default array size is 10.
Public ArrayList () {this (10);}
When an array of ArrayList elements expands, the algorithm that expands is: (current size) *3/2+1
int newcapacity = (oldcapacity * 3)/2 + 1;
Add (e-e) function:
Ensurecapacity (size + 1); Increments modcount!! elementdata[size++] = e;
Expands the array first, and then appends the new element to the end of the array.
Add (int index, E element) function:
Ensurecapacity (size+1); Increments modcount!! System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index); Elementdata[index] = element; size++;
The same is to expand the array first, then call System.arraycopy to adjust the array elements, and then insert the new element at the specified position index.
As a result, when adding elements to ArrayList, use the Add function as much as possible to make it more efficient.
Read elements are obtained directly from the Elementdata according to the subscript
Rangecheck (index); return (E) Elementdata[index];
Summarize:
ArrayList an array-based linear table, and it is not thread-safe. Read element efficiency is high, writing element efficiency is low.
Therefore ArrayList does not apply frequently to insert and delete operations.
This article is from the "Life in full" blog, be sure to keep this source http://shane.blog.51cto.com/824878/1828091
Java Collection class ArrayList source code Analysis