ArrayList的源码分析
我们平时创建列表的时候会经常使用ArrayList,它的源码究竟是什么样的,下面就来看一下我们常用的一些方法中的源码分析:
ArrayList继承了AbstractList,实现的接口有List、RandomAccess、Cloneable(可被克隆)、Serializable(支持序列化)
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
……
}
ArrayList 内部使用的动态数组来存储元素 ,初始化默认数组的大小是10。
1)初始化时候可以用默认大小来创建:ArrayList<Object> a = new ArrayList<>();
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
2)也可以根据实际大概的大小设定一个接近的初始大小:ArrayList<Object> b = new ArrayList<>(15); 其中15就是设置的一个初始大小值,根据实际可更改。设置这个初始大小如果实际够用就避免了扩容,当size的长度大于当前数组的长度时,就会进行一个扩容为当前长度的1.5倍,可能会浪费内存空间,扩容也会存在一定的耗时,后面说到扩容时候再细讲。
/**
* 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) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
ArrayList的常用方法:
(1)get(int index)方法,根据下标在列表中查找指定位置的元素。当要查找位置超过列表大小,会报异常,否则直接返回指定位置元素,这个是直接从底层数组根据下标获取的,它的时间复杂度是O(1)
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
(2)add(E e)方法,将指定元素追加到此列表的末尾。当不需要扩容时,时间复杂度为O(1)
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
首先要判断是否需要扩容
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);
}
如果需要扩容,以确保它至少可以容纳由最小容量参数指定的元素数量,扩容的时候,执行Arrays.copyOf()方法,把原有数组中的元素复制到扩容后的新数组当中,原数组被抛弃,会被GC回收。下面是扩容机制:
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
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;
}
(3)另一个add(int index, E element)方法,将指定元素插入到此列表中的指定位置。将当前位于该位置的元素(如果有的话)和所有后续元素向右移动(向它们的索引添加1)。
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
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++;
}
根据前面需要判断是否需要扩容,还要执行System.arraycopy()的拷贝方法,在数组中插入元素的时候,会把插入位置以后的元素依次往后复制,之后再通过 elementData[index] = element
将下标为index 的元素赋值为新的元素;随后执行 size = s + 1
,得到新的数组的长度。时间复杂度为O(n) 。
(4)indexOf(Object o),返回指定元素在列表中第一次出现的索引,如果列表中不包含该元素,则返回-1。因为要遍历列表,所以时间复杂度为O(n)
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
}
(5)set(int index, E element),用指定的元素替换此列表中指定位置的元素。直接从底层数组根据下标替换,时间复杂度为O(1)
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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;
}
(6)contains(Object o),如果这个列表包含指定的元素,返回true。也用到了上面(4)中的ndexOf(Object o)方法遍历列表查找。时间复杂度为O(n)
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
(7)remove(int index),移除此列表中指定位置的元素。将所有后续元素向左移动(从它们的索引中减去1)。当移除最后一个元素的时候,时间复杂度为O(1);当移除其它元素时,考虑到需要复制底层数组,所以时间复杂度为O(n)
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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;
}
(8)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;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
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
}
先要循环遍历列表找到要移除的元素,此时的时间复杂度已为O(n),当找到要移除的元素时,调用fastRemove()方法时,还要考虑到需要复制底层数组,时间复杂度还是O(n),整合在一起就是O(n)*O(n),也就是O(n²)
(9)clear(),从此列表中删除所有元素。此调用返回后,列表将为空。要遍历整个列表,因此时间复杂度为O(n)
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}