用途与特点
可用于存储有序数据,底层使用链表形式进行数据存储。 该集合理论上只要内存可以存放数据,就可以一直添加,是无限扩容的。
实现算法
底层使用Node的自定义对象进行存储,该对象中包含当前存储的数item、上一个节点prev、和下一个节点next 这三个属性来实现。但该链表是非环形,第一个first的prev为null,最后一个last的next为null,这样就形成了一下非闭环手拉手的效果。
LinkedList有3个主要属性size、first、last。
添加
添加与删除的操作逻辑基本相同,不再赘述。
/**
* Links e as first element.
*/
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++;
}
/**
* Links e as last element.
*/
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++;
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
查找
/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(index);
//根据传入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;
}
}
扩容机制
扩容时机:每次添加、删除都在扩容
是否线程安全,为什么?
非线程安全,因为在源码中未对数据的添加、删除、读取等做锁操作
根据jdk1.8版本源码解读