您的位置:首页 > 编程语言 > Java开发

java源码阅读系列-ArrayList

2017-11-07 15:31 465 查看

ArrayList

ArrayList是基于数组实现的,是一个动态数组,不是线程安全的,只能用在单线程环境中。在多线程环境下可以考虑Collection.synchronizedList(List 1)。

public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{ ...}这个是ArrayList的源码,可以看见实现Serializable接口,所以是可以序列化的;实现了RandomAccess接口,所以是可以随机访问的,实际上是通过下标序号进行快速访问;实现了Cloneable接口,所以是可以被克隆的。

下面继续看源码:

/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access

/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;可以看到两个私有属性,element和size
(1)element表示ArrayList里的元素(这里我们看到这个是用transient修饰的,这个是保证这个类不被序列化)

(2)size表示它包含语速的数量。

构造方法

(1)
/**
* 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);
}
}


这个构造方法是指定容量的一个列表,如果初始容量为0,则创建一个空列表,若小于0,抛出IllegalArgumentException异常。这个异常表示传递了一个不合适的参数。

(2)
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
默认的构造方法,创建一个空的列表。
(3)

/**
* 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();
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;
}
}

构造一个包含collection的元素的列表。

元素的存储

ArrayList共有五种元素存储方法
第一种:
/**
* 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) {
rangeCheck(index);//这是一个验证方法,关于边界越界的异常

E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
看注释我们可以知道:用指定的元素替换该列表中指定位置的元素。
这里调用了rangeCheck方法,这个方法的源码
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
这是一个验证方法,关于边界的异常。

继续往下看,调用了elementData()方法,这个方法就是返回一个E的类实例.

index表示要被替换的索引,elementData表示要被存储在这个索引位置的元素

第二种:
/**
* 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;
}


通过注释我们可以看到:将指定元素追加到该列表的末尾。

返回的是一个boolean类型的参数,这个无关紧要,知道就行。
方法的第一行调用了ensureCapacityInternal()方法,我们来看看方法源码
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}

ensureExplicitCapacity(minCapacity);
}
这是ArrayList扩容的方法。首先判断现在的ArrayList是不是空的,如果是空的,minCapaciy就取默认的容量和传入参数的最大值。之后再调用ensureExplicitCapacity()方法。方法源码:
private void ensureExplicitCapacity(int minCapacity) {
modCount++;

// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
首先计数器加一,然后判断现在的容量是不是大于了原来的容量,如果是,调用grow方法进行扩容。
grow方法:
/**
* 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);
}
首先看注释:增加容量,以确保它至少能容纳最小容量参数
4000
指定的元素个数。我们平常说,ArrayList的增加容量是1.5倍的,我们

第三种
/**
* 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) {
rangeCheckForAdd(index);

ensureCapacityInternal(size + 1);  // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
在指定位置插入一个元素,而这个位置后的元素向后移动一位。

这里我们可以看到这里调用了System.arraycopy方法,这个方法是将数组进行复制。
按照参数顺序为:原数组,原数要复制的起始位置,目标数组,目标数组的起始位置,复制的长度。
第四种
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator.  The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress.  (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
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;
}
这个是向指定列表插入集合c的所有元素。
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position.  Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices).  The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element from the
*              specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
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;
}
这个是在指定位置插入集合c的所有元素

移除元素

第一种
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 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;
}
移除制定的对象,这个类似indexof方法,实现原理是一样,都是遍历这个序列,放回需要的值就可以了。

第三种
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 void clear() {
modCount++;

// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;

size = 0;
}
移除全部元素。

第五种
/**
* Removes from this list all of the elements whose index is between
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
* Shifts any succeeding elements to the left (reduces their index).
* This call shortens the list by {@code (toIndex - fromIndex)} elements.
* (If {@code toIndex==fromIndex}, this operation has no effect.)
*
* @throws IndexOutOfBoundsException if {@code fromIndex} or
*         {@code toIndex} is out of range
*         ({@code fromIndex < 0 ||
*          fromIndex >= size() ||
*          toIndex > size() ||
*          toIndex < fromIndex})
*/
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;
}
删除列表两个下标的所有元素。这里我们看可以考到将toIndex后的元素全部符合到新的列表中。
这里我们可以看到有个有趣的注释//clear to et GC do its work.这里我们可以看到直接让GC来回收这些对象
第六种
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
将所有c集合的全部删除。
这个方法的对立面。retainAll()方法:保留全部 方法源码
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}


这里我们看看其他的方法
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
这里将多余的内存位置删除,首先我们要在搞清楚两个参数:size表示有多少个元素,length表示ArrayList申请的长度,一般length会是size的1.5倍,这里我们就是将length等于size。

get方法
public E get(int index) {
rangeCheck(index);

return elementData(index);
}
获取制定位置的元素。

好了,源码到这里差不多就结束了,如果你有心,继续往下看,还有一些内部类的源码,感情去可以去看看。

总结一下:

ArrayList是非线程安全的,所以我们在源码中常常可以看到有modcount这个变量,这个变量是ArrayList继承父类AbstracList的,如果你有看过其他的集合类,你会发现那些非线程安全的类都会有这个变量。这个变量的字面意思就改变次数。这个就和线程安全相关。
ArraayList里的我们可以看在插入和删除的操作的时候,会要移动后面的数组。这个是导致ArrayList插入和删除速度慢的原因。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: