直接上源码:java
构造函数:
算法
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this(10); }
其实arrayList的本质是一个数据,只不过这个数组的大小能够变化。咱们先来看下arraylist的数组是怎么定义的数组
/** * 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]; }
构造函数直接弄了一个10大小的obj对象数组。函数
this.elementData = new Object[initialCapacity];this
讲到这里咱们看下其实只有两个成员变量:spa
private static final long serialVersionUID = 8683452581122892189L; /** * 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;//元素 /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;//list元素数量
看他的核心方法:add
code
public boolean add(E e) { ensureCapacity(size + 1); // 添加元素的时候先让数量+1 elementData[size++] = e;//对应的数组引用放对应的对象 return true; }
这里面有个比较有意思的方法就是这个ensureCapacit这个方法里面有对应的扩展数组的算法:对象
public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length;//得到最初的数组大小,默认状况下初始值是10 if (minCapacity > oldCapacity) {//若是比原先的数组元素大了执行以下操做 Object oldData[] = elementData;//保存原有的数组元素 //从新new一个数组 int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: //从新生成一个数组对象并返回,生成的数组对象大小为原先的1.5X+1和minCapacity之间较大的那个 elementData = Arrays.copyOf(elementData, newCapacity); } }