1.ArrayList介绍
List有序地。ArrayList是实现了List的接口的动态数组。底层的是实现是数组,插入和移除元素的效率较慢
2.源码分析
1)成员变量
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData;
private int size
DEFAULT_CAPACITY :默认集合的大小,即ArrayList的初始化大小为10
EMPTY_ELEMENTDATA:这是一个空的数组
DEFAULTCAPACITY_EMPTY_ELEMENTDATA:大小为10的数组
elementData:集合实际操作进行增删改的数组
transient关键字:关闭序列化
size:记集合中的元素
2)构造函数
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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;
}
}
有三个构造函数
默认构造函数:提供一个指定容量为10的空列表
ArrayList(int initialCapacity):构造一个具有指定初始容量的空列表。并对初始化的大小进行检查,<0,抛出异常,=0,则为空列表
ArrayList(Collection< ? extends E> c):构造一个包含指定 collection 的元素的列表,直接用一个集合初始化另外一个集合。分析一下里面的代码,里面还是有挺多的知识点的。
将c转化为数组赋值给elementData
如果c不为空 1.调用toArray()方法将集合转化为数组 2)如果两个类型不一样(elementData.getClass和object.class)则通过Arrays.copyOf方法将类型进行转化,在方法中指定了类型
如果c为空 则elementData为一个空集合
3)add操作
ArrayList共有add(E e)、add(int index, E element)、addAll(Collection< ? extends E> c)、addAll(int index, Collection< ? extends E> c)四个王集合中添加元素的方法。所有的增加的方法都需要调用ensureCapacity方法进行扩容操作,并且在增加元素以后都会进行size++,元素计数值加1
add(E e)源码:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
进行扩容,并将指定的元素添加到列表的末尾
add(int index, E element)源码:
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++;
}
rangeCheckForAdd(index):会对加入位置的index进行检查,保证其不越界
接着进行扩容
在集合中间添加进元素需要进行数组拷贝,将index后面(包括index)的数组向后移动,空出index的位置,index前面的元素不发生变化。这里使用 System.arraycopy()的自我复制。对index位置的元素进行赋值,size++,因为添加元素(后面介绍的删除元素)都需要进行数组的拷贝,使得ArrayList相对于LinkedList的增删效率相比较低。
addAll(Collection< ? extends E> c)源码:
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;
}
首先将集合转化为数组,和之前的构造函数原理类似,因为其底层的实现是数组
numNew为传入集合的大小,进行扩容操作调用复制方法,最后增加size
addAll(int index, Collection< ? extends E> c)源码:
addAll(Collection< ? extends E> c)
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(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;
}
实现方式和上面的类似,只不过比上边多了数组的移动,并且是调用了两次System.arraycopy(),因为它不是从数组末尾插进的。首先是进行index的检查,凡是遇到随机插入元素必须对index进行检查。首先计算出需要扩容的大小进行扩容,在进行第一次的数组复制,将index后面numMoved个元素向后移动到末尾,空出加入集合的大小,第二次数组复制,将空出的位置用集合填了。完毕了
4)set方法
其实从结果看类似于插入操作,不过一般我们用它是用于修改集合中的元素
set(int index, E element)源码:
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
这个实现很简单,就是将指定位置的元素替换并返回旧值
5)remove方法:
共有remove(int index)、remove(Object o)、removeRange(int fromIndex, int toIndex)、removeAll()四个方法。实现思路和添加差不多,只不过删除不需要扩容,它实现的基本操作是将集合元素数量size删除以后进行修改,以及将数组置空
remove(int index)源码:
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;
}
删除指定位置上的元素,首先是检查index,modCount记录修改,增加一次。
取出index位置上的旧值后将index后面的元素向前移动,并将最后一个元素置为null,让垃圾收集器进行回收内存,最后返回旧值。这里有应用到泛型
remove(Object o)源码:
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;
}
删除指定的元素o,因为ArrayList中可以插入null,所以这里需要进行讨论,如果是null的话,使用==进行比较就可以了,找到相等的时候,删除index位置上的元素,如果不为null,则用equals进行比较。这里删除元素都调用的是fastRemove方法
fastRemove(int index)源码:
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
}
实现思路和remove(int index)一样,这里不多说
removeRange(int fromIndex, int toIndex)源码:
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
这个方法是将指定范围[fromIndex,toIndex)的元素删除
首先计算出需要向前移动的距离,进行数组移动。重新计算size的大小,使用for循环将后面的元素置为null让垃圾回收器回收。
removeAll(Collection < ? > c)源码:
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
调用批量删除方法
6)get方法
通过索引获得元素。ArrayList的查找效率较高,如果一个操作中是以查找操作为主的话建议使用ArrayList
get(int index)源码
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
很简单没什么可说的,集合是泛型的,所以返回类型为E根据实际类型来确定
2)扩容操作:
因为集合默认大小为10,当在集合中添加的元素超过10时,容器必须进行扩容
我们在上面add方法实现中调用的ensureCapacity(int minCapacity)方法,minCapacity传入的值是集合中元素的大小。ensureCapacity方法还会调用其它方法来实现,最终实现操作的是ensureExplicitCapacity这个方法
扩容操作源码:
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_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);
}
首先进行判断,实际集合的大小是不是等于10,(一般都是等于10的),如果需要进行扩容,即实际集合的大小大于10,才会调用ensureExplicitCapacity(minCapacity),在这个方法里,if判断肯定成立,然后调用ensureExplicitCapacity(int minCapacity),计算出需要扩容的大小,调用grow进行扩容,所以扩容的实现是由grow方法来完成的
grow源码:
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);
}
扩容并不是你需要增加几个元素,>>1相当于除以2,所以扩容是将数组变为原来的1.5倍,然后在和实际需要扩容的大小进行比较。总之扩容实现还是很巧妙的,1.5倍是最好的倍数,如果一次性扩容太小,需要多次对数组进行重新分配对象,对性能消耗比较严重。
最后进行数组的复制,重新生成新数组