*/
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;
复制代码
-
DEFAULT_CAPACITY:集合的默认容量,默认为10,通过new ArrayList() 创建List集合实例时的默认容量是10。
-
EMPTY_ELEMENTDATA:空数组,通过new ArrayList(0) 创建List集合实例时用的是这个空数组。
-
DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认容量空数组,这种是通过new ArrayList()无参构造方法创建集合时用的是这个空数组,与EMPTY_ELEMENTDATA的区别是在添加第一个元素时使用这个空数组的会初始化为DEFAULT_CAPACITY(10)个元素。
-
elementData:存储数据元素的数组,使用transient修饰,该字段不被序列化。
-
size:存储数据元素的个数,elementData数组的长度并不是存储数据元素的个数。\
3.ArrayList 构造方法
- 有参构造 ArrayList(int initialCapacity)
/**
-
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
-
传入初始容量,如果大于0就初始化elementData为对应大小,如果等于0就使用EMPTY_ELEMENTDATA空数组,
-
如果小于0抛出异常。
*/
// ArrayList(int initialCapacity)构造方法
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("不合理的初识容量: " +
initialCapacity);
}
}
复制代码
- 无参构造ArrayList()
/**
-
Constructs an empty list with an initial capacity of ten.
-
构造一个初始容量为10的空数组
-
不传初始容量,初始化为DEFAULTCAPACITY_EMPTY_ELEMENTDATA空数组,
-
会在添加第一个元素的时候扩容为默认的大小,即10。
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
复制代码
- 有参构造ArrayList(Collection c)
/**
-
Constructs a list containing the elements of the specified
-
collection, in the order they are returned by the collection’s
-
iterator.
-
把传入集合的元素初始化到ArrayList中
-
@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()返回的是不是Object[]类型,如果不是,重新拷贝成Object[].class类型
if (elementData.getClass() != Object[].class)
// 数组的创建与拷贝
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 如果c是空的集合,则初始化为空数组EMPTY_ELEMENTDATA
this.elementData = EMPTY_ELEMENTDATA;
}
}
复制代码
4. ArrayList 相关操作方法
添加操作
**1.add(E e)添加元素到集合中
添加元素到末尾,平均时间复杂度为O(1):**
/**
-
Appends the specified element to the end of this list.
-
添加元素到末尾,平均时间复杂度为O(1)