一、ArrayList
概述
ArrayList实现List接口,底层用数组保存元素。元素数量趋向容量时,数组容量会动态增长,此时会带来数据的拷贝,允许包括null元素。线程不安全,如果多个线程同时访问一个 ArrayList 实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。(结构上的修改是指任何添加或删除一个或多个元素的操作,或者显式调整底层数组的大小;仅仅设置元素的值不是结构上的修改。)
实现的接口
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
}
ArrayList 继承了 AbstractList,实现了 List。它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。ArrayList 实现了 RandmoAccess 接口,我们即可以通过元素的序号快速获取元素对象。ArrayList 实现了 Cloneable 接口,即覆盖了函数 clone(),能被克隆。ArrayList 实现 java.io.Serializable 接口,这意味着 ArrayList 支持序列化,能通过序列化去传输。
数据结构
底层使用数组实现列表,随机访问的效率很高。
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
构造器
分为默认初始容量为10的空List、指定容量的空List、构造包含指定Collection的List(顺序是该Collection迭代器返回的顺序)。
public ArrayList() {
this(10);
}
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
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);
}
存储
1.set(int index, E element):检查是否越界,设置新值,返回旧值。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
2.add(E e):添加元素到List尾部,容量不足时扩展数组,扩展的大小一般是原大小的1.5倍。int newCapacity = oldCapacity + (oldCapacity >> 1);
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
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);
}
3.add(int index, E element):在 index 位置插入 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++;
}
读取
public E get(int index) {
rangeCheck(index);
return (E) elementData[index];
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
删除
1.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; // Let gc do its work
return oldValue;
}
2.remove(Object o):删除特定某一元素。元素分为null和非null两种情况(该List中允许存放null作为元素),找到后都是用由后向前覆盖的方法删除该元素。
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
}
快速失败机制
ArrayList是线程不安全的,每个线程在自己的工作内存中修改了链表的结构,便有可能抛出ConcurrentModificationException。这里不展开讨论,将在其他的地方专门说明。
二、LinkedList
概述
LinkedList实现List接口,底层用双向链表保存元素。由于是用链表实现,插入和删除操作变得高效,不存在扩容问题,但是访问指定元素的效率差。允许包括null元素。线程不安全。
实现的接口
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{}
AbstractSequenceList 提供了List接口骨干性的实现以减少实现 List 接口的复杂度。Deque 接口定义了双端队列的操作。
数据结构
LinkedList内部用双向链表实现List,每一个节点维护分别指向前面一个节点和后一个节点的引用变量(Node)。
private static class Node<E> {
E item;
//指向前一个节点
Node<E> next;
//指向后一个节点
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
构造器
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
存储
1.addFirst()、addLast()、addLast():List头部插入一个节点,该节点向前指向null,向后指向旧头节点,尾部插入节点类似。可以看到头节点的向前指针、尾节点的向后指针都是指向null。
public void addFirst(E e) {
linkFirst(e);
}
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
public void addLast(E e) {
linkLast(e);
}
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
public boolean add(E e) {
linkLast(e);
return true;
}
2.set(int index, E element)、add(int index, E element):首先会去检查是否越界,然后在node(int index)中找到指定下标的节点,如果下标小于一半,从头节点开始寻找,否则从尾节点开始寻找(这也是LinkedList访问操作效率低的原因,不能像数组一样随机访问)。add(int index, E element)类似,也会用到node(int index)找到指定节点,然后执行插入操作(双向链表的插入操作效率高,而数组的插入需要移动数组,所以效率低)。
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
读取
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
删除
从头开始找到该元素并且删除(元素可以是null),成功返回true,失败返回false。
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
三、总结
ArrayList底层使用数组作为数据结构,set()、get()等操作的效率高,add()、delete()、remove()等操作可能涉及部分数组元素的整体移动,所以效率低下。LinkedList利用了双向链表作为数据结构,在头尾增删元素效率高,在中间增删元素伴随着顺序查找,但是增删操作很简单,不必移动大量元素,访问指定节点也伴随着顺序查找过程。