ArrayList创建和add等各种api使用原理
- ArrayList 允许空值和重复元素,当往 ArrayList 中添加的元素数量大于其底层数组容量时,其会通过 扩容 机制重新生成一个更大的数组。
- ArrayList 是非线程安全类,并发环境下,多个线程同时操作 ArrayList,会引发不可预知的异常或错误。
(文章中有超级福利)
ArrayList创建源码
- 带有初始容量的构造方法
// Shared empty array instance used for empty instances.
private static final Object[] EMPTY_ELEMENTDATA = {
};
/**
* 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) {
// 参数大于0,elementData初始化为initialCapacity大小的数组,即根据传入的参数大小创建数组
if (initialCapacity > 0) {
this.elementData = new Object\[initialCapacity\];
// 参数等于0,创建空数组
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
// 否则抛出异常,参数异常,初始化容量异常
} else {
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
}
}
- 无参构造方法,即使用默认的size为10的空数组,
在构造方法中没有对数组长度进行设置,会在后续调用add方法的时候进行扩容
/**
* 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 = {
};
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY\_EMPTY\_ELEMENTDATA;
}
- 参数为集合的构造方法,将一个参数为Collection的集合转变为ArrayList(实际上就是将集合中的元素换为了数组的形式)。
/**
* 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) {
// 如果传入的集合为空,则c.toArray()抛出空指针异常
elementData = c.toArray();
// 如果传入的数组容量不为0 而且toArray之后不为对象数组的话,就通过数组复制修改为底层结构是对象数组的集合
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass()