0 前言
与 ArrayList 一样实现了 List 接口,只是 LinkedList 底层结构为链表.在插入和删除时更优于 ArrayList,而随机访问则比 ArrayList 稍逊.
其允许元素包括 null.除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。
该类还实现了 Deque 接口,为 add、poll 提供先进先出队列操作,以及其他堆栈和双端队列操作。
所有操作都是按照双重链接列表的需要执行的。在列表中编索引的操作将从开头或结尾遍历列表(从靠近指定索引的一端).
1 继承体系
LinkedList 继承自 AbstractSequentialList,又实现了 List、Deque、Cloneable、Serializable等接口.
AbstractSequentialList相较于AbstractList(ArrayList的父类),只支持次序访问,而不支持随机访问,因为它的get(int index) ,set(int index, E element), add(int index, E element), remove(int index) 都是基于迭代器实现的。
Deque - 线性 collection,支持在两端插入和移除元素,定义了双端队列的操作.
2 属性
双向链表定义方式.
头节点的指针.不变性约束条件:(first == null && last == null) || (first.prev == null && first.item != null)
尾节点的指针.不变性约束条件:(first == null && last == null) || (last.next == null && last.item != null)
表示 LinkedList 的大小
节点Node
可以看出,这是一个典型的双向链表的结构
3 构造方法
3.1 无参
- 构造一个空list
3.2 有参
- 构造一个包含指定 collection 中的元素的list,这些元素按其 collection 的迭代器返回的顺序排列。
- 下面开始看各大核心 API 细节.
4 add
4.1 末尾添加
add(E e)
- 将指定元素添加到此 list 的末尾
- linkLast(E e)
- add(E e)等价于addLast(E e),因为 LinkedList 实现了 Deque 接口.
addLast(E e)
核心都是linkLast方法.
- 图解末尾添加