LinkedList
文章目录
【注意】最后更新于 February 12, 2017,文中内容可能已过时,请谨慎使用。
一、 LinkedList概述:
- LinkedList双向链表实现。
- LinkedList实现List,Deque接口,提供栈、队列、双端队列的方法。
- LinkedList不是线程安全。
- LinkedList实现RandomAccess, Cloneable和java.io.Serializable接口。RandomAccess支持快速随机访问。Cloneable能被克隆。Serializable支持序列化。
二、 LinkedList实现:
-
(1).LinkedList实现双向链表结构(Node)。E是泛型
1 2 3 4 5 6 7 8 9 10 11 12 13
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; } }
-
(2).定义入口访问链表数据结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * 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;
-
(3).元素操作 - 添加到首部(addFirst)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public void addFirst(E e) { linkFirst(e); } /** * Links e as first element. * 往首节点(first)插入新节点 */ 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++; }
-
添加到尾部(addLast)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public void addLast(E e) { linkLast(e); } /** * Links e as last element. * 往尾节点(last)插入新节点 */ 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++; }
-
(4).删除
|
|
- (5).Iterator 迭代器实现
|
|
-
(6).subList实现只是一个视图
- 继承AbstractList
-
(7).转换数组对象
|
|
三、 总结:
- 插入和删除操作时比ArrayList更加高效,因为它是基于链表的。
- 查询元素比ArrayList慢,最坏情况都要遍历size/2(size»1)。 - 按索引查询时,先判断索引位置,size的一半就用fist遍历,否就是用last遍历
- LinkedList双链表。next下节点,prev上节点。
- 也实现fail-fast机制实现,逻辑跟ArrayList一样。都是modCount做判断。
- SubList只是一个LinkedList视图,实现AbstractList。