在分析ArrayList源码以前,先看一下ArrayList在数据结构中的位置,常见的数据结构按照逻辑结构跟存储结构以下:数组
先看看源码的注释:安全
很明显,ArrayList是一个线性结构,底层经过数组实现,而且是动态数组。bash
下面看一下ArrayList的继承关系,这个是经过IDEA生成的继承关系图,很清晰,终于不用本身画了。数据结构
经过图能够看到ArrayList继承自AbstractList,而且实现了List, RandomAccess, Cloneable, Serializable接口,而AbstractList实现了Collection接口,则ArrayList具备Collection的全部方法,并且可以进行clone,序列化,下面开始开始对ArrayList的源码进行分析,吼吼。dom
//序列化ID
private static final long serialVersionUID = 8683452581122892189L;
//默认的初始化数组的容量为10
private static final int DEFAULT_CAPACITY = 10;
//共享的空数组,也就是调用空的构造方法的时候会进行默认用这个数组进行初始化
private static final Object[] EMPTY_ELEMENTDATA = {};
//数组缓冲区,也就是历来存放List元素的数组。ArrayList的容量就是缓冲区数组的长度。对于一个空数组,在添加第一个元素的时候,List的容量会被设置成默认的DEFAULT_CAPACITY,也就是10,
transient Object[] elementData;
//elementData的长度
private int size;复制代码
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}复制代码
前面有提到过,当初始化数组为空的时候,在add的时候会进行判断,若是数组的长度为0,数组的长度就是默认的数组长度ide
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}复制代码
这个跟上面的区别在于建立了一个新的数组,数组的最大长度就是传入的初始化容量,数组的长度为0。性能
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);
}复制代码
数组的长度就是传入的集合的长度,将集合传入缓冲数组ui
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}复制代码
public void add(int index, E element) {
//判断index是否合乎规范
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//检查是否须要扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//拷贝数组
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//进行赋值
elementData[index] = element;
//将数组的长度自增
size++;
}复制代码
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}复制代码
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}复制代码
Add操做有如上几个重载方法,仔细观察一下,大同小异,咱们选择第二个重载方法,也就是在指定位置添加一个元素:this
这里面比较有养分的就是第二步了,下面重点分析第二步:spa
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}复制代码
传入了此时数组须要的长度,只要数组为初始化的时候没有指定容量,就会在minCapacity(size+1)跟DEFAULT_CAPACITY中间取一个最大值,之因此这样,是由于若是将数组的容量设置成过小,会致使数组频繁的扩容,影响性能。
private void ensureExplicitCapacity(int minCapacity) {
//这个变量来自于ArrayList的父类AbstractList,主要用来记录集合的操做次数
modCount++;
// overflow-conscious code
//若是此时须要的数组长度大于数组自己的长度,则进行扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}复制代码
private void grow(int minCapacity) {
// overflow-conscious code
//数组当前的容量
int oldCapacity = elementData.length;
//扩容后新数组的容量,增大了0.5倍
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);
}复制代码
public E remove(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;
E oldValue = (E) 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 boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//此时执行的代码就是删除指定位置的代码
private void fastRemove(int index) {
modCount++;
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
}复制代码
仔细观察一下上面两个重载方法,实际上是差很少的,删除元素分两步走:
比较简单,不过多描述
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}复制代码
直接替换掉对应的元素
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;
}复制代码
这些都是经过遍历对元素进行查找,一个是从头至尾遍历,一个是从未到头遍历,查到结构就返回对应的下表,不然返回-1.
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}复制代码
ArrayList的特色
关于ArrayList的源码就分析到这里,由于底层的实现是数组,因此无论是扩容仍是其它的增删改查操做都是对数组进行操做,因此只要对数组足够了解,基本上仍是挺好理解的。