集合框架(六)

LinkedList

LinkedList实现了Deque(双向的Queue)接口,和ArrayList和Vector相比,LinkedList的实现方式完全不同。ArrayList和Vector底层都是以数组实现的。而LinkedList是利用对象本身来存储对象,借助记录前一个对象和后一个对象的引用完成对所有对象的遍历。其中有一个存储对象的内部类Node<>,其实现方式如下:

private static class Node {
E item;
Node next;
Node prev;

Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}

LinkedList使用Node类代替了数组,根据自身存储的prev和next索引逐个遍历所有对象。因此不适合随机查找,随机查找的get(int)方法实现如下:

public E get(int index) {
checkElementIndex(index);
return node(index).item;
}

Node node(int index) {
// assert isElementIndex(index);

if (index < (size >> 1)) {
Node x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}

可见每次随机查找都要逐一遍历。因此,随机访问元素使用ArrayList要比LinkedList要快很多。

再看看LinkedList的add(E)方法:

public boolean add(E e) {
linkLast(e);
return true;
}

void linkLast(E e) {
final Node l = last;
final Node newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}

LinkedList每次添加元素都要创建Node对象,而ArrayList仅仅使用数组。

posted @ 2016-08-08 22:30  DeadGhost  阅读(137)  评论(0)    收藏  举报