Source code:
Constructor:
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this(10); }
In fact, the essence of arraylist is a data, but the size of this array can be changed. Let's first look at how the array of arraylist is defined.
/** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @exception IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; }
The constructor directly obtains an array of 10 OBJ objects.
This. elementdata = new object [initialcapacity];
Here, we can see that there are actually only two member variables:
Private Static final long serialversionuid = 8683452583162892189l;/*** the Array Buffer into which the elements of the arraylist are stored. * The capacity of the arraylist is the length of this array buffer. */private transient object [] elementdata; // element/*** the size of the arraylist (the number of elements it contains ). ** @ serial */private int size; // Number of list elements
Look at his core method: add
Public Boolean add (E) {ensurecapacity (size + 1); // Add the number of elements + 1 elementdata [size ++] = E; // put the corresponding object return true for the corresponding array reference ;}
An interesting method is that the ensurecapacit method contains an algorithm for extending the array:
Public void ensurecapacity (INT mincapacity) {modcount ++; int oldcapacity = elementdata. length; // obtain the initial array size. The default value is 10 if (mincapacity> oldcapacity) {// if it is larger than the original array element, perform the following operation: Object olddata [] = elementdata; // Save the original array element // re-create an array int newcapacity = (oldcapacity * 3)/2 + 1; if (newcapacity <mincapacity) newcapacity = mincapacity; // mincapacity is usually close to size, so this is a win: // regenerate an array object and return, the generated array object is the larger elementdata = arrays between 1.5x + 1 and mincapacity. copyof (elementdata, newcapacity );}}