我们在平时开发的过程中,ArrayList绝对是最常用的集合之一,首先基于JDK1.7我们来看一看它的底层代码。 我们先看一下它的继承关系图:
ArrayList
共继承了一个抽象类,实现了4个接口
-
List
接口,主要提供数组的添加、删除、修改、迭代遍历等操作。 -
Cloneable
接口,表示ArrayList支持克隆。 -
RandomAccess
接口,表示ArrayList支持快速
的随机访问。 -
Serializable
接口,表示ArrayList支持序列化的功能。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
复制代码
构造方法
ArrayList
有三个构造方法
- 初始化指定容量
- 初始化未指定容量,使用默认数组
- 使用集合作为elementData
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
super();
this.elementData = 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();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
复制代码
新增方法
ArrayList
中的新增方法有四个
- public boolean add(E e) //在数组中
顺序
新增一条 - public void add(int index,E element) //在数组中
指定位置
添加数据 - public boolean addAll(Collection<? extends E> c) //在数组中
顺序
新增多个元素 - public boolean addAll(int index, Collection<? extends E> c) //在数组中
指定位置
新增多个元素
我们重点看一下add
方法,会先判断是否需要进行扩容,如果需要扩容则进行扩容,最后将数据添加到数组的最后边,如果初始化是没有指定长度,以及长度< DEFAULT_CAPACITY
,都会默认将数组长度赋值成DEFAULT_CAPACITY
,也就是有种懒加载的味道,当新数据添加后的长度大于原数组长度时进行扩容grow
public boolean add(E e) {
//判断是否需要扩容,需要的话进行扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//将数据添加到数组最后边
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//空数组,默认赋值数组长度为DEFAULT_CAPACITY=10
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
复制代码
grow
具体内容如下,扩容机制,扩容量=旧数组容量右移1位(相当于除2并向下取整的结果):
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
复制代码
需要注意的一点是add(int index,E element)
,addAll(int index, Collection<? extends E> c)
,这两个方法都是在指定位置添加元素,首先进行越界检查,在检查数组是否足够大,随后在进行数据挪动,此处用的是System.arraycopy
复制方法,只不过源数组和目标数组都是elementData
自己,相当于将指定位置及以后的数据向后移动N位,最后把新增的数据添加到指定位置。
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
复制代码
删除方法
删除元素的方法主要有4个,分别为如下所示:
public E remove(int index)
移除指定位置的元素,并返回该位置的原元素。public boolean remove(Object o)
移除首个为 o 的元素,并返回是否移除成功。protected void removeRange(int fromIndex, int toIndex)
批量移除[fromIndex, toIndex)
内的多个元素,这里需要特别注意:toIndex
不包括的噢。public boolean removeAll(Collection<?> c)
批量移除指定的多个元素。
查看删除相关方法,会发现大致可以分为两步:
- 找到指定位置的数据,进行删除操作
- 指定位置后的数据进行前移,
size
调整
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
复制代码
查找数据
查找数据的方法,两个区别就在于一个从数组前方遍历,一个从数组后边遍历
public int indexOf(Object o)
public int lastIndexOf(Object o)
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
复制代码
查找的代码不难,不过从代码里面可以看出来ArrayList
是支持存储 null
的