线程安全
ArrayList 和 LinkedList 都是不同步的,也就是不保证线程安全。
底层数据结构
(源码版本:JDK1.8)
查看 ArrayList 源码,定位到其某个构造器看它初始化过程:
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);
}
}
再回去看其成员变量:
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 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
不难看出它的底层使用了 Object 数组。
再来看看 LinkedList 的成员变量:
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
再进入 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;
}
}
很明显能看出它的底层是一个双向链表。
需要注意的是,JDK1.6 及之前版本为循环双向链表,JDK1.7 开始取消了循环。
插入和删除
ArrayList 采用数组存储,所以插入和删除元素的时间复杂度受元素位置的影响。
例如,执行add(E e)方法的时候,ArrayList 会将指定的元素追加到此列表的末尾,此时时间复杂度为 O(1)。
但是,如果要在指定位置 i 插入元素的话,即调用add(int index,E element)方法,时间复杂度就变为 O(n-i) 了,因为在进行上述操作的时候数组中第 i 和第 i 个元素之后的 n-i 个元素都要执行向后移动一位的操作。
LinkedList 采用链表存储,所以插入和删除元素的时间复杂度不受元素位置的影响。
如果要在指定位置 i 插入和删除元素的话时间复杂度为 O(i) ,因为移动需要耗费时间。
随机访问
快速随机访问就是通过元素的序号快速获取元素对象。(对应get(int index)
方法)
LinkedList 不支持高效的随机元素访问,而 ArrayList 支持。
ArrayList 源码实现了 RandomAccess 接口,可以作为佐证。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
进入该接口:
public interface RandomAccess {}
发现它是空的,根据官方注释可以得知它的用途在于提醒开发者选择恰当的算法,以便在应用于随机或顺序访问列表时提供良好的性能。
所以,RandomAccess 接口只是作为标识,并不是说 ArrayList 实现了它才具有快速随机访问的功能。
实现了 RandomAccess 接口的 list,优先选择普通 for 循环遍历。
未实现 RandomAccess 接口的 list ,优先选择迭代器(iterator)遍历。
内存空间占用
ArrayList 的额外空间开销主要体现在顺序表的结尾会预留一定的容量空间。
而 LinkedList 则体现在它的每一个元素都需要消耗比 ArrayList 更多的空间,因为要存放直接后继、直接前驱以及数据。