手撕ArrayList
1.源码结构
Resizable-array implementation of the <tt>List</tt> interface. Implements2.重图解的角度分析ArrayList ,重点为扩容机制,初始化机制
all optional list operations, and permits all elements, including
<tt>null</tt>. In addition to implementing the <tt>List</tt> interface,
this class provides methods to manipulate the size of the array that is
used internally to store the list. (This class is roughly equivalent to
<tt>Vector</tt>, except that it is unsynchronized.)
API的使用并非使用的重点,我所要掌握的是从ArrayList的源码感受其数据结构的使用理解
①属性部分
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.工具而已
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.工具而已,就是为了与上面的区分在第一次添加数据时如何确定扩容机制
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access 底层实际存储数据的数据结构即为数组
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
②初始化部分
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];//传入初始容量
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;//与默认初始空数组作区分使用,这种虽然是空数组,但是这是传入的初始容量为0,有着本质区别
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//默认一般都是这种,不需要传入初始容量
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;//这个与传入初始容量为0的一样
}
}
③添加到扩容机制