先看一段代码:
public static void main(String[] args) {
List arrayList = new ArrayList();
//获取当前时间毫秒数
long currentTime = System.currentTimeMillis();
for (int i = 0; i < 300000; i++) {//给ArrayList添加30w个元素,添加到第一个位置
arrayList.add(0, new Object());
}
//输出ArrayList添加30w个元素耗时
System.out.println("arrayList添加300000个元素耗时:" + (System.currentTimeMillis() - currentTime));
List linkedList = new LinkedList();
currentTime = System.currentTimeMillis();//重新获取当前时间
for (int i = 0; i < 300000; i++) {//给LinkedList添加30w个元素,添加到第一个位置
linkedList.add(0, new Object());
}
//输出ArrayList添加30w个元素耗时
System.out.println("linkedList添加300000个元素耗时:" + (System.currentTimeMillis() - currentTime));
Random rand = new Random();
currentTime = System.currentTimeMillis();
for (int i = 0; i < arrayList.size(); i++) {
arrayList.get(rand.nextInt(300000));//随机获取一个位置的元素
}
//输出ArrayList获取30w次元素耗时
System.out.println("arrayList取出300000次元素耗时:" + (System.currentTimeMillis() - currentTime));
currentTime = System.currentTimeMillis();
for (int i = 0; i < linkedList.size(); i++) {
linkedList.get(rand.nextInt(300000));//随机获取一个位置的元素
}
//输出LinkedList获取30w次元素耗时
System.out.println("linkedList取出300000次元素耗时:" + (System.currentTimeMillis() - currentTime));
}
运行结果:
arrayList添加300000个元素耗时:8126
linkedList添加300000个元素耗时:16
arrayList取出300000个元素耗时:16
linkedList取出300000个元素耗时:193169
可以看到,ArrayList添加元素比Linked添加元素慢,但在取出元素时,ArrayList消耗的时间远远低于LinkedList。
因为ArrayList是由动态数组实现的,在一个位置插入数据,如果这个位置不是位于最后,这个位置及其后面的元素都要往后面进行移动,如图 1-1。
图 1-1
而LinkedList是链表实现,在添加元素到指定位置时,只需将元素进行连接即可,如图1-2。
图 1-2
在取出元素时,ArrayList只需根据下标获取指定位置的元素即可,但LinkedList由于是使用链表实现的,不可以直接通过下标进行获取指定元素。下面是LinkedList的get实现代码:
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
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;
}
}
这段代码的意思是,如果下标小于LinkedList的元素数量的一半,则从第一个元素开始往后遍历寻找,否则从最后一个元素开始往前遍历寻找,直到找到指定位置的元素。也就是说LinkedList获取元素需要一个个遍历判断,并且元素个数越多,寻找元素需要的时间越长。
总结: ArrayList与LinkedList各有优缺点,ArrayList添加删除元素比较慢,但是取出元素比LinkedList快,而LinkedList添加删除元素比较快,但如果是经常要取出元素并且数据量比较大就可以尝试使用ArrayList。