一.介绍

LinkedList简介

LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。
LinkedList 实现 List 接口,能对它进行队列操作。
LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。
LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆。
LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。
LinkedList 是非同步的。

LinkedList构造函数

  1. // 默认构造函数
  2. LinkedList() // 创建一个LinkedList,保护Collection中的全部元素。
  3. LinkedList(Collection<? extends E> collection)

LinkedList的API

  1. LinkedListAPI
  2. boolean add(E object) //将指定的元素的列表。
  3. void add(int location, E object) //在指定位置插入指定元素在这个列表中。
  4. boolean addAll(Collection<? extends E> collection) //将指定集合的所有元素附加到这个列表,它们的顺序返回的指定集合的迭代器。
  5. boolean addAll(int location, Collection<? extends E> collection)//将指定集合中的所有元素插入此列表,从指定的位置。
  6. void addFirst(E object) //将某个元素添加到列表的头部
  7. void addLast(E object) //将某个元素添加到列表的尾部
  8. void clear() //从这个列表中删除所有的元素。
  9. Object clone() //返回一个 LinkedList浅拷贝。
  10. boolean contains(Object object) //返回 true如果该列表包含指定的元素。
  11. Iterator<E> descendingIterator() //返回一个迭代器在反向双端队列中的元素顺序排列的。
  12. E element() //检索,但不删除这个列表的头(第一个元素)。
  13. E get(int location) //返回此列表的元素在指定的位置。
  14. E getFirst() //返回此列表的第一个元素。
  15. E getLast() //返回此列表中最后一个元素。
  16. int indexOf(Object object) //返回第一次出现的指定元素的索引列表,或1如果该列表不包含的元素。
  17. int lastIndexOf(Object object) //返回最后出现的指定元素的索引列表,或1如果该列表不包含的元素。
  18. ListIterator<E> listIterator(int location) //返回一个list-iterator这个列表的元素(在适当的序列),开始在指定的位置在列表中。
  19. boolean offer(E o) //添加指定的元素作为这个列表的尾部(最后一个元素)。
  20. boolean offerFirst(E e) //插入指定元素在这个列表的前面。
  21. boolean offerLast(E e) //插入指定元素在这个列表。
  22. E peek() //检索,但不删除这个列表的头(第一个元素)。
  23. E peekFirst() //检索,但不删除这个列表的第一个元素,或返回 null如果该列表是空的。
  24. E peekLast() //检索,但不删除最后一个元素的列表,或返回 null如果该列表是空的。
  25. E poll() //获取和删除这个列表的头(第一个元素)。
  26. E pollFirst() //获取和删除这个列表的第一个元素,或返回 null如果该列表是空的。
  27. E pollLast() //获取和删除最后一个元素的列表,或返回 null如果该列表是空的。
  28. E pop() //从堆栈中弹出一个元素代表了这个列表。
  29. void push(E e) //将一个元素放入堆栈中由这个列表。
  30. E remove() //获取和删除这个列表的头(第一个元素)。
  31. E remove(int location) //这个列表中删除指定位置的元素。
  32. boolean remove(Object object) //删除第一次出现的指定元素从这个列表,如果它存在。
  33. E removeFirst() //从这个列表中删除并返回第一个元素。
  34. boolean removeFirstOccurrence(Object o) //删除第一次出现的指定元素在这个列表(从头到尾遍历列表时)。
  35. E removeLast() //从这个列表中删除并返回最后一个元素。
  36. boolean removeLastOccurrence(Object o) //删除此列表中最后出现的指定元素(如果从头到尾遍历列表)。
  37. E set(int location, E object) //取代在指定位置上的元素在此列表中指定的元素。
  38. int size() //返回此列表的元素数量。
  39. <T> T[] toArray(T[] contents) //返回一个数组,其中包含所有的元素在这个列表中正确的顺序(从第一个到最后一个元素),返回数组的运行时类型是指定数组中
  40. Object[] toArray() //返回一个数组,其中包含所有的元素在这个列表中适当顺序(从第一个到最后一个元素)。

AbstractSequentialList简介

在介绍LinkedList的源码之前,先介绍一下AbstractSequentialList。毕竟,LinkedList是AbstractSequentialList的子类。

AbstractSequentialList 实现了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)这些函数。这些接口都是随机访问List的,LinkedList是双向链表;既然它继承于AbstractSequentialList,就相当于已经实现了“get(int index)这些接口”。

此外,我们若需要通过AbstractSequentialList自己实现一个列表,只需要扩展此类,并提供 listIterator() 和 size() 方法的实现即可。若要实现不可修改的列表,则需要实现列表迭代器的 hasNext、next、hasPrevious、previous 和 index 方法即可。

二.数据结构

LinkedList的继承关系

  1. java.lang.Object
  2. java.util.AbstractCollection<E>
  3. java.util.AbstractList<E>
  4. java.util.AbstractSequentialList<E>
  5. java.util.LinkedList<E>
  6. public class LinkedList<E>
  7. extends AbstractSequentialList<E>
  8. implements List<E>, Deque<E>, Cloneable, java.io.Serializable {}

LinkedList与Collection关系如下图:

LinkedList详细介绍(源码解析)和使用示例 - 图1

LinkedList的本质是双向链表。
(01) LinkedList继承于AbstractSequentialList,并且实现了Dequeue接口。
(02) LinkedList包含两个重要的成员:header 和 size。
  header是双向链表的表头,它是双向链表节点所对应的类Entry的实例。Entry中包含成员变量: previous, next, element。其中,previous是该节点的上一个节点,next是该节点的下一个节点,element是该节点所包含的值。
  size是双向链表中节点的个数。

三.源码解析(基于JDK1.6.0_45)

为了更了解LinkedList的原理,下面对LinkedList源码代码作出分析

在阅读源码之前,我们先对LinkedList的整体实现进行大致说明:
LinkedList实际上是通过双向链表去实现的。既然是双向链表,那么它的顺序访问会非常高效,而随机访问效率比较低
既然LinkedList是通过双向链表的,但是它也实现了List接口{也就是说,它实现了get(int location)、remove(int location)等“根据索引值来获取、删除节点的函数”}。LinkedList是如何实现List的这些接口的,如何将“双向链表和索引值联系起来的”?
实际原理非常简单,它就是通过一个计数索引值来实现的。例如,当我们调用get(int location)时,首先会比较“location”和“双向链表长度的1/2”;若前者大,则从链表头开始往后查找,直到location位置;否则,从链表末尾开始先前查找,直到location位置。
这就是“双线链表和索引值联系起来”的方法。

好了,接下来开始阅读源码(只要理解双向链表,那么LinkedList的源码很容易理解的)。

  1. package java.util;
  2. public class LinkedList<E>
  3. extends AbstractSequentialList<E>
  4. implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  5. {
  6. // 链表的表头,表头不包含任何数据。Entry是个链表类数据结构。
  7. private transient Entry<E> header = new Entry<E>(null, null, null);
  8. // LinkedList中元素个数
  9. private transient int size = 0;
  10. // 默认构造函数:创建一个空的链表
  11. public LinkedList() {
  12. header.next = header.previous = header;
  13. }
  14. // 包含“集合”的构造函数:创建一个包含“集合”的LinkedList
  15. public LinkedList(Collection<? extends E> c) {
  16. this();
  17. addAll(c);
  18. }
  19. // 获取LinkedList的第一个元素
  20. public E getFirst() {
  21. if (size==0)
  22. throw new NoSuchElementException();
  23. // 链表的表头header中不包含数据。
  24. // 这里返回header所指下一个节点所包含的数据。
  25. return header.next.element;
  26. }
  27. // 获取LinkedList的最后一个元素
  28. public E getLast() {
  29. if (size==0)
  30. throw new NoSuchElementException();
  31. // 由于LinkedList是双向链表;而表头header不包含数据。
  32. // 因而,这里返回表头header的前一个节点所包含的数据。
  33. return header.previous.element;
  34. }
  35. // 删除LinkedList的第一个元素
  36. public E removeFirst() {
  37. return remove(header.next);
  38. }
  39. // 删除LinkedList的最后一个元素
  40. public E removeLast() {
  41. return remove(header.previous);
  42. }
  43. // 将元素添加到LinkedList的起始位置
  44. public void addFirst(E e) {
  45. addBefore(e, header.next);
  46. }
  47. // 将元素添加到LinkedList的结束位置
  48. public void addLast(E e) {
  49. addBefore(e, header);
  50. }
  51. // 判断LinkedList是否包含元素(o)
  52. public boolean contains(Object o) {
  53. return indexOf(o) != -1;
  54. }
  55. // 返回LinkedList的大小
  56. public int size() {
  57. return size;
  58. }
  59. // 将元素(E)添加到LinkedList中
  60. public boolean add(E e) {
  61. // 将节点(节点数据是e)添加到表头(header)之前。
  62. // 即,将节点添加到双向链表的末端。
  63. addBefore(e, header);
  64. return true;
  65. }
  66. // 从LinkedList中删除元素(o)
  67. // 从链表开始查找,如存在元素(o)则删除该元素并返回true;
  68. // 否则,返回false。
  69. public boolean remove(Object o) {
  70. if (o==null) {
  71. // 若o为null的删除情况
  72. for (Entry<E> e = header.next; e != header; e = e.next) {
  73. if (e.element==null) {
  74. remove(e);
  75. return true;
  76. }
  77. }
  78. } else {
  79. // 若o不为null的删除情况
  80. for (Entry<E> e = header.next; e != header; e = e.next) {
  81. if (o.equals(e.element)) {
  82. remove(e);
  83. return true;
  84. }
  85. }
  86. }
  87. return false;
  88. }
  89. // 将“集合(c)”添加到LinkedList中。
  90. // 实际上,是从双向链表的末尾开始,将“集合(c)”添加到双向链表中。
  91. public boolean addAll(Collection<? extends E> c) {
  92. return addAll(size, c);
  93. }
  94. // 从双向链表的index开始,将“集合(c)”添加到双向链表中。
  95. public boolean addAll(int index, Collection<? extends E> c) {
  96. if (index < 0 || index > size)
  97. throw new IndexOutOfBoundsException("Index: "+index+
  98. ", Size: "+size);
  99. Object[] a = c.toArray();
  100. // 获取集合的长度
  101. int numNew = a.length;
  102. if (numNew==0)
  103. return false;
  104. modCount++;
  105. // 设置“当前要插入节点的后一个节点”
  106. Entry<E> successor = (index==size ? header : entry(index));
  107. // 设置“当前要插入节点的前一个节点”
  108. Entry<E> predecessor = successor.previous;
  109. // 将集合(c)全部插入双向链表中
  110. for (int i=0; i<numNew; i++) {
  111. Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
  112. predecessor.next = e;
  113. predecessor = e;
  114. }
  115. successor.previous = predecessor;
  116. // 调整LinkedList的实际大小
  117. size += numNew;
  118. return true;
  119. }
  120. // 清空双向链表
  121. public void clear() {
  122. Entry<E> e = header.next;
  123. // 从表头开始,逐个向后遍历;对遍历到的节点执行一下操作:
  124. // (01) 设置前一个节点为null
  125. // (02) 设置当前节点的内容为null
  126. // (03) 设置后一个节点为“新的当前节点”
  127. while (e != header) {
  128. Entry<E> next = e.next;
  129. e.next = e.previous = null;
  130. e.element = null;
  131. e = next;
  132. }
  133. header.next = header.previous = header;
  134. // 设置大小为0
  135. size = 0;
  136. modCount++;
  137. }
  138. // 返回LinkedList指定位置的元素
  139. public E get(int index) {
  140. return entry(index).element;
  141. }
  142. // 设置index位置对应的节点的值为element
  143. public E set(int index, E element) {
  144. Entry<E> e = entry(index);
  145. E oldVal = e.element;
  146. e.element = element;
  147. return oldVal;
  148. }
  149. // 在index前添加节点,且节点的值为element
  150. public void add(int index, E element) {
  151. addBefore(element, (index==size ? header : entry(index)));
  152. }
  153. // 删除index位置的节点
  154. public E remove(int index) {
  155. return remove(entry(index));
  156. }
  157. // 获取双向链表中指定位置的节点
  158. private Entry<E> entry(int index) {
  159. if (index < 0 || index >= size)
  160. throw new IndexOutOfBoundsException("Index: "+index+
  161. ", Size: "+size);
  162. Entry<E> e = header;
  163. // 获取index处的节点。
  164. // 若index < 双向链表长度的1/2,则从前先后查找;
  165. // 否则,从后向前查找。
  166. if (index < (size >> 1)) {
  167. for (int i = 0; i <= index; i++)
  168. e = e.next;
  169. } else {
  170. for (int i = size; i > index; i--)
  171. e = e.previous;
  172. }
  173. return e;
  174. }
  175. // 从前向后查找,返回“值为对象(o)的节点对应的索引”
  176. // 不存在就返回-1
  177. public int indexOf(Object o) {
  178. int index = 0;
  179. if (o==null) {
  180. for (Entry e = header.next; e != header; e = e.next) {
  181. if (e.element==null)
  182. return index;
  183. index++;
  184. }
  185. } else {
  186. for (Entry e = header.next; e != header; e = e.next) {
  187. if (o.equals(e.element))
  188. return index;
  189. index++;
  190. }
  191. }
  192. return -1;
  193. }
  194. // 从后向前查找,返回“值为对象(o)的节点对应的索引”
  195. // 不存在就返回-1
  196. public int lastIndexOf(Object o) {
  197. int index = size;
  198. if (o==null) {
  199. for (Entry e = header.previous; e != header; e = e.previous) {
  200. index--;
  201. if (e.element==null)
  202. return index;
  203. }
  204. } else {
  205. for (Entry e = header.previous; e != header; e = e.previous) {
  206. index--;
  207. if (o.equals(e.element))
  208. return index;
  209. }
  210. }
  211. return -1;
  212. }
  213. // 返回第一个节点
  214. // 若LinkedList的大小为0,则返回null
  215. public E peek() {
  216. if (size==0)
  217. return null;
  218. return getFirst();
  219. }
  220. // 返回第一个节点
  221. // 若LinkedList的大小为0,则抛出异常
  222. public E element() {
  223. return getFirst();
  224. }
  225. // 删除并返回第一个节点
  226. // 若LinkedList的大小为0,则返回null
  227. public E poll() {
  228. if (size==0)
  229. return null;
  230. return removeFirst();
  231. }
  232. // 将e添加双向链表末尾
  233. public boolean offer(E e) {
  234. return add(e);
  235. }
  236. // 将e添加双向链表开头
  237. public boolean offerFirst(E e) {
  238. addFirst(e);
  239. return true;
  240. }
  241. // 将e添加双向链表末尾
  242. public boolean offerLast(E e) {
  243. addLast(e);
  244. return true;
  245. }
  246. // 返回第一个节点
  247. // 若LinkedList的大小为0,则返回null
  248. public E peekFirst() {
  249. if (size==0)
  250. return null;
  251. return getFirst();
  252. }
  253. // 返回最后一个节点
  254. // 若LinkedList的大小为0,则返回null
  255. public E peekLast() {
  256. if (size==0)
  257. return null;
  258. return getLast();
  259. }
  260. // 删除并返回第一个节点
  261. // 若LinkedList的大小为0,则返回null
  262. public E pollFirst() {
  263. if (size==0)
  264. return null;
  265. return removeFirst();
  266. }
  267. // 删除并返回最后一个节点
  268. // 若LinkedList的大小为0,则返回null
  269. public E pollLast() {
  270. if (size==0)
  271. return null;
  272. return removeLast();
  273. }
  274. // 将e插入到双向链表开头
  275. public void push(E e) {
  276. addFirst(e);
  277. }
  278. // 删除并返回第一个节点
  279. public E pop() {
  280. return removeFirst();
  281. }
  282. // 从LinkedList开始向后查找,删除第一个值为元素(o)的节点
  283. // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点
  284. public boolean removeFirstOccurrence(Object o) {
  285. return remove(o);
  286. }
  287. // 从LinkedList末尾向前查找,删除第一个值为元素(o)的节点
  288. // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点
  289. public boolean removeLastOccurrence(Object o) {
  290. if (o==null) {
  291. for (Entry<E> e = header.previous; e != header; e = e.previous) {
  292. if (e.element==null) {
  293. remove(e);
  294. return true;
  295. }
  296. }
  297. } else {
  298. for (Entry<E> e = header.previous; e != header; e = e.previous) {
  299. if (o.equals(e.element)) {
  300. remove(e);
  301. return true;
  302. }
  303. }
  304. }
  305. return false;
  306. }
  307. // 返回“index到末尾的全部节点”对应的ListIterator对象(List迭代器)
  308. public ListIterator<E> listIterator(int index) {
  309. return new ListItr(index);
  310. }
  311. // List迭代器
  312. private class ListItr implements ListIterator<E> {
  313. // 上一次返回的节点
  314. private Entry<E> lastReturned = header;
  315. // 下一个节点
  316. private Entry<E> next;
  317. // 下一个节点对应的索引值
  318. private int nextIndex;
  319. // 期望的改变计数。用来实现fail-fast机制。
  320. private int expectedModCount = modCount;
  321. // 构造函数。
  322. // 从index位置开始进行迭代
  323. ListItr(int index) {
  324. // index的有效性处理
  325. if (index < 0 || index > size)
  326. throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);
  327. // 若 “index 小于 ‘双向链表长度的一半’”,则从第一个元素开始往后查找;
  328. // 否则,从最后一个元素往前查找。
  329. if (index < (size >> 1)) {
  330. next = header.next;
  331. for (nextIndex=0; nextIndex<index; nextIndex++)
  332. next = next.next;
  333. } else {
  334. next = header;
  335. for (nextIndex=size; nextIndex>index; nextIndex--)
  336. next = next.previous;
  337. }
  338. }
  339. // 是否存在下一个元素
  340. public boolean hasNext() {
  341. // 通过元素索引是否等于“双向链表大小”来判断是否达到最后。
  342. return nextIndex != size;
  343. }
  344. // 获取下一个元素
  345. public E next() {
  346. checkForComodification();
  347. if (nextIndex == size)
  348. throw new NoSuchElementException();
  349. lastReturned = next;
  350. // next指向链表的下一个元素
  351. next = next.next;
  352. nextIndex++;
  353. return lastReturned.element;
  354. }
  355. // 是否存在上一个元素
  356. public boolean hasPrevious() {
  357. // 通过元素索引是否等于0,来判断是否达到开头。
  358. return nextIndex != 0;
  359. }
  360. // 获取上一个元素
  361. public E previous() {
  362. if (nextIndex == 0)
  363. throw new NoSuchElementException();
  364. // next指向链表的上一个元素
  365. lastReturned = next = next.previous;
  366. nextIndex--;
  367. checkForComodification();
  368. return lastReturned.element;
  369. }
  370. // 获取下一个元素的索引
  371. public int nextIndex() {
  372. return nextIndex;
  373. }
  374. // 获取上一个元素的索引
  375. public int previousIndex() {
  376. return nextIndex-1;
  377. }
  378. // 删除当前元素。
  379. // 删除双向链表中的当前节点
  380. public void remove() {
  381. checkForComodification();
  382. Entry<E> lastNext = lastReturned.next;
  383. try {
  384. LinkedList.this.remove(lastReturned);
  385. } catch (NoSuchElementException e) {
  386. throw new IllegalStateException();
  387. }
  388. if (next==lastReturned)
  389. next = lastNext;
  390. else
  391. nextIndex--;
  392. lastReturned = header;
  393. expectedModCount++;
  394. }
  395. // 设置当前节点为e
  396. public void set(E e) {
  397. if (lastReturned == header)
  398. throw new IllegalStateException();
  399. checkForComodification();
  400. lastReturned.element = e;
  401. }
  402. // 将e添加到当前节点的前面
  403. public void add(E e) {
  404. checkForComodification();
  405. lastReturned = header;
  406. addBefore(e, next);
  407. nextIndex++;
  408. expectedModCount++;
  409. }
  410. // 判断 “modCount和expectedModCount是否相等”,依次来实现fail-fast机制。
  411. final void checkForComodification() {
  412. if (modCount != expectedModCount)
  413. throw new ConcurrentModificationException();
  414. }
  415. }
  416. // 双向链表的节点所对应的数据结构。
  417. // 包含3部分:上一节点,下一节点,当前节点值。
  418. private static class Entry<E> {
  419. // 当前节点所包含的值
  420. E element;
  421. // 下一个节点
  422. Entry<E> next;
  423. // 上一个节点
  424. Entry<E> previous;
  425. /**
  426. * 链表节点的构造函数。
  427. * 参数说明:
  428. * element —— 节点所包含的数据
  429. * next —— 下一个节点
  430. * previous —— 上一个节点
  431. */
  432. Entry(E element, Entry<E> next, Entry<E> previous) {
  433. this.element = element;
  434. this.next = next;
  435. this.previous = previous;
  436. }
  437. }
  438. // 将节点(节点数据是e)添加到entry节点之前。
  439. private Entry<E> addBefore(E e, Entry<E> entry) {
  440. // 新建节点newEntry,将newEntry插入到节点e之前;并且设置newEntry的数据是e
  441. Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
  442. newEntry.previous.next = newEntry;
  443. newEntry.next.previous = newEntry;
  444. // 修改LinkedList大小
  445. size++;
  446. // 修改LinkedList的修改统计数:用来实现fail-fast机制。
  447. modCount++;
  448. return newEntry;
  449. }
  450. // 将节点从链表中删除
  451. private E remove(Entry<E> e) {
  452. if (e == header)
  453. throw new NoSuchElementException();
  454. E result = e.element;
  455. e.previous.next = e.next;
  456. e.next.previous = e.previous;
  457. e.next = e.previous = null;
  458. e.element = null;
  459. size--;
  460. modCount++;
  461. return result;
  462. }
  463. // 反向迭代器
  464. public Iterator<E> descendingIterator() {
  465. return new DescendingIterator();
  466. }
  467. // 反向迭代器实现类。
  468. private class DescendingIterator implements Iterator {
  469. final ListItr itr = new ListItr(size());
  470. // 反向迭代器是否下一个元素。
  471. // 实际上是判断双向链表的当前节点是否达到开头
  472. public boolean hasNext() {
  473. return itr.hasPrevious();
  474. }
  475. // 反向迭代器获取下一个元素。
  476. // 实际上是获取双向链表的前一个节点
  477. public E next() {
  478. return itr.previous();
  479. }
  480. // 删除当前节点
  481. public void remove() {
  482. itr.remove();
  483. }
  484. }
  485. // 返回LinkedList的Object[]数组
  486. public Object[] toArray() {
  487. // 新建Object[]数组
  488. Object[] result = new Object[size];
  489. int i = 0;
  490. // 将链表中所有节点的数据都添加到Object[]数组中
  491. for (Entry<E> e = header.next; e != header; e = e.next)
  492. result[i++] = e.element;
  493. return result;
  494. }
  495. // 返回LinkedList的模板数组。所谓模板数组,即可以将T设为任意的数据类型
  496. public <T> T[] toArray(T[] a) {
  497. // 若数组a的大小 < LinkedList的元素个数(意味着数组a不能容纳LinkedList中全部元素)
  498. // 则新建一个T[]数组,T[]的大小为LinkedList大小,并将该T[]赋值给a。
  499. if (a.length < size)
  500. a = (T[])java.lang.reflect.Array.newInstance(
  501. a.getClass().getComponentType(), size);
  502. // 将链表中所有节点的数据都添加到数组a中
  503. int i = 0;
  504. Object[] result = a;
  505. for (Entry<E> e = header.next; e != header; e = e.next)
  506. result[i++] = e.element;
  507. if (a.length > size)
  508. a[size] = null;
  509. return a;
  510. }
  511. // 克隆函数。返回LinkedList的克隆对象。
  512. public Object clone() {
  513. LinkedList<E> clone = null;
  514. // 克隆一个LinkedList克隆对象
  515. try {
  516. clone = (LinkedList<E>) super.clone();
  517. } catch (CloneNotSupportedException e) {
  518. throw new InternalError();
  519. }
  520. // 新建LinkedList表头节点
  521. clone.header = new Entry<E>(null, null, null);
  522. clone.header.next = clone.header.previous = clone.header;
  523. clone.size = 0;
  524. clone.modCount = 0;
  525. // 将链表中所有节点的数据都添加到克隆对象中
  526. for (Entry<E> e = header.next; e != header; e = e.next)
  527. clone.add(e.element);
  528. return clone;
  529. }
  530. // java.io.Serializable的写入函数
  531. // 将LinkedList的“容量,所有的元素值”都写入到输出流中
  532. private void writeObject(java.io.ObjectOutputStream s)
  533. throws java.io.IOException {
  534. // Write out any hidden serialization magic
  535. s.defaultWriteObject();
  536. // 写入“容量”
  537. s.writeInt(size);
  538. // 将链表中所有节点的数据都写入到输出流中
  539. for (Entry e = header.next; e != header; e = e.next)
  540. s.writeObject(e.element);
  541. }
  542. // java.io.Serializable的读取函数:根据写入方式反向读出
  543. // 先将LinkedList的“容量”读出,然后将“所有的元素值”读出
  544. private void readObject(java.io.ObjectInputStream s)
  545. throws java.io.IOException, ClassNotFoundException {
  546. // Read in any hidden serialization magic
  547. s.defaultReadObject();
  548. // 从输入流中读取“容量”
  549. int size = s.readInt();
  550. // 新建链表表头节点
  551. header = new Entry<E>(null, null, null);
  552. header.next = header.previous = header;
  553. // 从输入流中将“所有的元素值”并逐个添加到链表中
  554. for (int i=0; i<size; i++)
  555. addBefore((E)s.readObject(), header);
  556. }
  557. }

总结
(01) LinkedList 实际上是通过双向链表去实现的。
它包含一个非常重要的内部类:Entry。Entry是双向链表节点所对应的数据结构,它包括的属性有:当前节点所包含的值上一个节点下一个节点
(02) 从LinkedList的实现方式中可以发现,它不存在LinkedList容量不足的问题。
(03) LinkedList的克隆函数,即是将全部元素克隆到一个新的LinkedList对象中。
(04) LinkedList实现java.io.Serializable。当写入到输出流时,先写入“容量”,再依次写入“每一个节点保护的值”;当读出输入流时,先读取“容量”,再依次读取“每一个元素”。
(05) 由于LinkedList实现了Deque,而Deque接口定义了在双端队列两端访问元素的方法。提供插入、移除和检查元素的方法。每种方法都存在两种形式:一种形式在操作失败时抛出异常,另一种形式返回一个特殊值(null 或 false,具体取决于操作)。

总结起来如下表格:

        第一个元素(头部)                 最后一个元素(尾部)
        抛出异常        特殊值            抛出异常        特殊值
插入    addFirst(e)    offerFirst(e)    addLast(e)        offerLast(e)
移除    removeFirst()  pollFirst()      removeLast()    pollLast()
检查    getFirst()     peekFirst()      getLast()        peekLast()

(06) LinkedList可以作为FIFO(先进先出)的队列,作为FIFO的队列时,下表的方法等价:

队列方法       等效方法
add(e)        addLast(e)
offer(e)      offerLast(e)
remove()      removeFirst()
poll()        pollFirst()
element()     getFirst()
peek()        peekFirst()

LinkedList详细介绍(源码解析)和使用示例 - 图2; “复制代码”)

(07) LinkedList可以作为LIFO(后进先出)的栈,作为LIFO的栈时,下表的方法等价:

栈方法 等效方法
push(e) addFirst(e)
pop() removeFirst()
peek() peekFirst()

四.遍历方式

LinkedList遍历方式

LinkedList支持多种遍历方式。建议不要采用随机访问的方式去遍历LinkedList,而采用逐个遍历的方式。
(01) 第一种,通过迭代器遍历。即通过Iterator去遍历。

for(Iterator iter = list.iterator(); iter.hasNext();)
    iter.next();

(02) 通过快速随机访问遍历LinkedList

int size = list.size();
for (int i=0; i<size; i++) {
    list.get(i);        
}

(03) 通过另外一种for循环来遍历LinkedList

for (Integer integ:list) 
    ;

(04) 通过pollFirst()来遍历LinkedList

while(list.pollFirst() != null)
    ;

(05) 通过pollLast()来遍历LinkedList

while(list.pollLast() != null)
    ;

(06) 通过removeFirst()来遍历LinkedList

try {
    while(list.removeFirst() != null)
        ;
} catch (NoSuchElementException e) {
}

(07) 通过removeLast()来遍历LinkedList

try {
    while(list.removeLast() != null)
        ;
} catch (NoSuchElementException e) {
}

测试这些遍历方式效率的代码如下

import java.util.List;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

/*
 * @desc 测试LinkedList的几种遍历方式和效率
 *
 * @author skywang
 */
public class LinkedListThruTest {
    public static void main(String[] args) {
        // 通过Iterator遍历LinkedList
        iteratorLinkedListThruIterator(getLinkedList()) ;

        // 通过快速随机访问遍历LinkedList
        iteratorLinkedListThruForeach(getLinkedList()) ;

        // 通过for循环的变种来访问遍历LinkedList
        iteratorThroughFor2(getLinkedList()) ;

        // 通过PollFirst()遍历LinkedList
        iteratorThroughPollFirst(getLinkedList()) ;

        // 通过PollLast()遍历LinkedList
        iteratorThroughPollLast(getLinkedList()) ;

        // 通过removeFirst()遍历LinkedList
        iteratorThroughRemoveFirst(getLinkedList()) ;

        // 通过removeLast()遍历LinkedList
        iteratorThroughRemoveLast(getLinkedList()) ;
    }

    private static LinkedList getLinkedList() {
        LinkedList llist = new LinkedList();
        for (int i=0; i<100000; i++)
            llist.addLast(i);

        return llist;
    }
    /**
     * 通过快迭代器遍历LinkedList
     */
    private static void iteratorLinkedListThruIterator(LinkedList<Integer> list) {
        if (list == null)
            return ;

        // 记录开始时间
        long start = System.currentTimeMillis();

        for(Iterator iter = list.iterator(); iter.hasNext();)
            iter.next();

        // 记录结束时间
        long end = System.currentTimeMillis();
        long interval = end - start;
        System.out.println("iteratorLinkedListThruIterator:" + interval+" ms");
    }

    /**
     * 通过快速随机访问遍历LinkedList
     */
    private static void iteratorLinkedListThruForeach(LinkedList<Integer> list) {
        if (list == null)
            return ;

        // 记录开始时间
        long start = System.currentTimeMillis();

        int size = list.size();
        for (int i=0; i<size; i++) {
            list.get(i);        
        }
        // 记录结束时间
        long end = System.currentTimeMillis();
        long interval = end - start;
        System.out.println("iteratorLinkedListThruForeach:" + interval+" ms");
    }

    /**
     * 通过另外一种for循环来遍历LinkedList
     */
    private static void iteratorThroughFor2(LinkedList<Integer> list) {
        if (list == null)
            return ;

        // 记录开始时间
        long start = System.currentTimeMillis();

        for (Integer integ:list) 
            ;

        // 记录结束时间
        long end = System.currentTimeMillis();
        long interval = end - start;
        System.out.println("iteratorThroughFor2:" + interval+" ms");
    }

    /**
     * 通过pollFirst()来遍历LinkedList
     */
    private static void iteratorThroughPollFirst(LinkedList<Integer> list) {
        if (list == null)
            return ;

        // 记录开始时间
        long start = System.currentTimeMillis();
        while(list.pollFirst() != null)
            ;

        // 记录结束时间
        long end = System.currentTimeMillis();
        long interval = end - start;
        System.out.println("iteratorThroughPollFirst:" + interval+" ms");
    }

    /**
     * 通过pollLast()来遍历LinkedList
     */
    private static void iteratorThroughPollLast(LinkedList<Integer> list) {
        if (list == null)
            return ;

        // 记录开始时间
        long start = System.currentTimeMillis();
        while(list.pollLast() != null)
            ;

        // 记录结束时间
        long end = System.currentTimeMillis();
        long interval = end - start;
        System.out.println("iteratorThroughPollLast:" + interval+" ms");
    }

    /**
     * 通过removeFirst()来遍历LinkedList
     */
    private static void iteratorThroughRemoveFirst(LinkedList<Integer> list) {
        if (list == null)
            return ;

        // 记录开始时间
        long start = System.currentTimeMillis();
        try {
            while(list.removeFirst() != null)
                ;
        } catch (NoSuchElementException e) {
        }

        // 记录结束时间
        long end = System.currentTimeMillis();
        long interval = end - start;
        System.out.println("iteratorThroughRemoveFirst:" + interval+" ms");
    }

    /**
     * 通过removeLast()来遍历LinkedList
     */
    private static void iteratorThroughRemoveLast(LinkedList<Integer> list) {
        if (list == null)
            return ;

        // 记录开始时间
        long start = System.currentTimeMillis();
        try {
            while(list.removeLast() != null)
                ;
        } catch (NoSuchElementException e) {
        }

        // 记录结束时间
        long end = System.currentTimeMillis();
        long interval = end - start;
        System.out.println("iteratorThroughRemoveLast:" + interval+" ms");
    }

}

执行结果

iteratorLinkedListThruIterator:8 ms
iteratorLinkedListThruForeach:3724 ms
iteratorThroughFor2:5 ms
iteratorThroughPollFirst:8 ms
iteratorThroughPollLast:6 ms
iteratorThroughRemoveFirst:2 ms
iteratorThroughRemoveLast:2 ms

由此可见,遍历LinkedList时,使用removeFist()或removeLast()效率最高。但用它们遍历时,会删除原始数据;若单纯只读取,而不删除,应该使用第3种遍历方式。
无论如何,千万不要通过随机访问去遍历LinkedList!

五.api示例

下面通过一个示例来学习如何使用LinkedList的常用API

import java.util.List;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

/*
 * @desc LinkedList测试程序。
 *
 * @author skywang
 * @email  kuiwu-wang@163.com
 */
public class LinkedListTest {
    public static void main(String[] args) {
        // 测试LinkedList的API
        testLinkedListAPIs() ;

        // 将LinkedList当作 LIFO(后进先出)的堆栈
        useLinkedListAsLIFO();

        // 将LinkedList当作 FIFO(先进先出)的队列
        useLinkedListAsFIFO();
    }

    /*
     * 测试LinkedList中部分API
     */
    private static void testLinkedListAPIs() {
        String val = null;
        //LinkedList llist;
        //llist.offer("10");
        // 新建一个LinkedList
        LinkedList llist = new LinkedList();
        //---- 添加操作 ----
        // 依次添加1,2,3
        llist.add("1");
        llist.add("2");
        llist.add("3");

        // 将“4”添加到第一个位置
        llist.add(1, "4");


        System.out.println("\nTest \"addFirst(), removeFirst(), getFirst()\"");
        // (01) 将“10”添加到第一个位置。  失败的话,抛出异常!
        llist.addFirst("10");
        System.out.println("llist:"+llist);
        // (02) 将第一个元素删除。        失败的话,抛出异常!
        System.out.println("llist.removeFirst():"+llist.removeFirst());
        System.out.println("llist:"+llist);
        // (03) 获取第一个元素。          失败的话,抛出异常!
        System.out.println("llist.getFirst():"+llist.getFirst());


        System.out.println("\nTest \"offerFirst(), pollFirst(), peekFirst()\"");
        // (01) 将“10”添加到第一个位置。  返回true。
        llist.offerFirst("10");
        System.out.println("llist:"+llist);
        // (02) 将第一个元素删除。        失败的话,返回null。
        System.out.println("llist.pollFirst():"+llist.pollFirst());
        System.out.println("llist:"+llist);
        // (03) 获取第一个元素。          失败的话,返回null。
        System.out.println("llist.peekFirst():"+llist.peekFirst());


        System.out.println("\nTest \"addLast(), removeLast(), getLast()\"");
        // (01) 将“20”添加到最后一个位置。  失败的话,抛出异常!
        llist.addLast("20");
        System.out.println("llist:"+llist);
        // (02) 将最后一个元素删除。        失败的话,抛出异常!
        System.out.println("llist.removeLast():"+llist.removeLast());
        System.out.println("llist:"+llist);
        // (03) 获取最后一个元素。          失败的话,抛出异常!
        System.out.println("llist.getLast():"+llist.getLast());


        System.out.println("\nTest \"offerLast(), pollLast(), peekLast()\"");
        // (01) 将“20”添加到第一个位置。  返回true。
        llist.offerLast("20");
        System.out.println("llist:"+llist);
        // (02) 将第一个元素删除。        失败的话,返回null。
        System.out.println("llist.pollLast():"+llist.pollLast());
        System.out.println("llist:"+llist);
        // (03) 获取第一个元素。          失败的话,返回null。
        System.out.println("llist.peekLast():"+llist.peekLast());



        // 将第3个元素设置300。不建议在LinkedList中使用此操作,因为效率低!
        llist.set(2, "300");
        // 获取第3个元素。不建议在LinkedList中使用此操作,因为效率低!
        System.out.println("\nget(3):"+llist.get(2));


        // ---- toArray(T[] a) ----
        // 将LinkedList转行为数组
        String[] arr = (String[])llist.toArray(new String[0]);
        for (String str:arr) 
            System.out.println("str:"+str);

        // 输出大小
        System.out.println("size:"+llist.size());
        // 清空LinkedList
        llist.clear();
        // 判断LinkedList是否为空
        System.out.println("isEmpty():"+llist.isEmpty()+"\n");

    }

    /**
     * 将LinkedList当作 LIFO(后进先出)的堆栈
     */
    private static void useLinkedListAsLIFO() {
        System.out.println("\nuseLinkedListAsLIFO");
        // 新建一个LinkedList
        LinkedList stack = new LinkedList();

        // 将1,2,3,4添加到堆栈中
        stack.push("1");
        stack.push("2");
        stack.push("3");
        stack.push("4");
        // 打印“栈”
        System.out.println("stack:"+stack);

        // 删除“栈顶元素”
        System.out.println("stack.pop():"+stack.pop());

        // 取出“栈顶元素”
        System.out.println("stack.peek():"+stack.peek());

        // 打印“栈”
        System.out.println("stack:"+stack);
    }

    /**
     * 将LinkedList当作 FIFO(先进先出)的队列
     */
    private static void useLinkedListAsFIFO() {
        System.out.println("\nuseLinkedListAsFIFO");
        // 新建一个LinkedList
        LinkedList queue = new LinkedList();

        // 将10,20,30,40添加到队列。每次都是插入到末尾
        queue.add("10");
        queue.add("20");
        queue.add("30");
        queue.add("40");
        // 打印“队列”
        System.out.println("queue:"+queue);

        // 删除(队列的第一个元素)
        System.out.println("queue.remove():"+queue.remove());

        // 读取(队列的第一个元素)
        System.out.println("queue.element():"+queue.element());

        // 打印“队列”
        System.out.println("queue:"+queue);
    }
}

运行结果

Test "addFirst(), removeFirst(), getFirst()"
llist:[10, 1, 4, 2, 3]
llist.removeFirst():10
llist:[1, 4, 2, 3]
llist.getFirst():1

Test "offerFirst(), pollFirst(), peekFirst()"
llist:[10, 1, 4, 2, 3]
llist.pollFirst():10
llist:[1, 4, 2, 3]
llist.peekFirst():1

Test "addLast(), removeLast(), getLast()"
llist:[1, 4, 2, 3, 20]
llist.removeLast():20
llist:[1, 4, 2, 3]
llist.getLast():3

Test "offerLast(), pollLast(), peekLast()"
llist:[1, 4, 2, 3, 20]
llist.pollLast():20
llist:[1, 4, 2, 3]
llist.peekLast():3

get(3):300
str:1
str:4
str:300
str:3
size:4
isEmpty():true


useLinkedListAsLIFO
stack:[4, 3, 2, 1]
stack.pop():4
stack.peek():3
stack:[3, 2, 1]

useLinkedListAsFIFO
queue:[10, 20, 30, 40]
queue.remove():10
queue.element():20
queue:[20, 30, 40]