LinkedList中文版注释
package java.util;
2
3 public class LinkedList<E>
4 extends AbstractSequentialList<E>
5 implements List<E>, Deque<E>, Cloneable, java.io.Serializable
6 {
7 // 链表的表头,表头不包含任何数据。Entry是个链表类数据结构。 8 private transient Entry<E> header = new Entry<E>(null, null, null);
9
10 // LinkedList中元素个数
11 private transient int size = 0;
12
13 // 默认构造函数:创建一个空的链表 14 public LinkedList() {
15 header.next = header.previous = header;
16 }
17
18 // 包含“集合”的构造函数:创建一个包含“集合”的LinkedList 19 public LinkedList(Collection<? extends E> c) {
20 this();
21 addAll(c);
22 }
23
24 // 获取LinkedList的第一个元素 25 public E getFirst() {
26 if (size==0)
27 throw new NoSuchElementException();
28
29 // 链表的表头header中不包含数据。
30 // 这里返回header所指下一个节点所包含的数据。 31 return header.next.element;
32 }
33
34 // 获取LinkedList的最后一个元素 35 public E getLast() {
36 if (size==0)
37 throw new NoSuchElementException();
38
39 // 由于LinkedList是双向链表;而表头header不包含数据。
40 // 因而,这里返回表头header的前一个节点所包含的数据。 41 return header.previous.element;
42 }
43
44 // 删除LinkedList的第一个元素 45 public E removeFirst() {
46 return remove(header.next);
47 }
48
49 // 删除LinkedList的最后一个元素 50 public E removeLast() {
51 return remove(header.previous);
52 }
53
54 // 将元素添加到LinkedList的起始位置 55 public void addFirst(E e) {
56 addBefore(e, header.next);
57 }
58
59 // 将元素添加到LinkedList的结束位置 60 public void addLast(E e) {
61 addBefore(e, header);
62 }
63
64 // 判断LinkedList是否包含元素(o) 65 public boolean contains(Object o) {
66 return indexOf(o) != -1;
67 }
68
69 // 返回LinkedList的大小 70 public int size() {
71 return size;
72 }
73
74 // 将元素(E)添加到LinkedList中 75 public boolean add(E e) {
76 // 将节点(节点数据是e)添加到表头(header)之前。
77 // 即,将节点添加到双向链表的末端。 78 addBefore(e, header);
79 return true;
80 }
81
82 // 从LinkedList中删除元素(o)
83 // 从链表开始查找,如存在元素(o)则删除该元素并返回true;
84 // 否则,返回false。 85 public boolean remove(Object o) {
86 if (o==null) {
87 // 若o为null的删除情况 88 for (Entry<E> e = header.next; e != header; e = e.next) {
89 if (e.element==null) {
90 remove(e);
91 return true;
92 }
93 }
94 } else {
95 // 若o不为null的删除情况 96 for (Entry<E> e = header.next; e != header; e = e.next) {
97 if (o.equals(e.element)) {
98 remove(e);
99 return true;
100 }
101 }
102 }
103 return false;
104 }
105
106 // 将“集合(c)”添加到LinkedList中。
107 // 实际上,是从双向链表的末尾开始,将“集合(c)”添加到双向链表中。108 public boolean addAll(Collection<? extends E> c) {
109 return addAll(size, c);
110 }
111
112 // 从双向链表的index开始,将“集合(c)”添加到双向链表中。113 public boolean addAll(int index, Collection<? extends E> c) {
114 if (index < 0 || index > size)
115 throw new IndexOutOfBoundsException("Index: "+index+
116 ", Size: "+size);
117 Object[] a = c.toArray();
118 // 获取集合的长度119 int numNew = a.length;
120 if (numNew==0)
121 return false;
122 modCount++;
123
124 // 设置“当前要插入节点的后一个节点”125 Entry<E> successor = (index==size ? header : entry(index));
126 // 设置“当前要插入节点的前一个节点”127 Entry<E> predecessor = successor.previous;
128 // 将集合(c)全部插入双向链表中129 for (int i=0; i<numNew; i++) {
130 Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
131 predecessor.next = e;
132 predecessor = e;
133 }
134 successor.previous = predecessor;
135
136 // 调整LinkedList的实际大小137 size += numNew;
138 return true;
139 }
140
141 // 清空双向链表142 public void clear() {
143 Entry<E> e = header.next;
144 // 从表头开始,逐个向后遍历;对遍历到的节点执行一下操作:
145 // (01) 设置前一个节点为null
146 // (02) 设置当前节点的内容为null
147 // (03) 设置后一个节点为“新的当前节点”148 while (e != header) {
149 Entry<E> next = e.next;
150 e.next = e.previous = null;
151 e.element = null;
152 e = next;
153 }
154 header.next = header.previous = header;
155 // 设置大小为0156 size = 0;
157 modCount++;
158 }
159
160 // 返回LinkedList指定位置的元素161 public E get(int index) {
162 return entry(index).element;
163 }
164
165 // 设置index位置对应的节点的值为element166 public E set(int index, E element) {
167 Entry<E> e = entry(index);
168 E oldVal = e.element;
169 e.element = element;
170 return oldVal;
171 }
172
173 // 在index前添加节点,且节点的值为element174 public void add(int index, E element) {
175 addBefore(element, (index==size ? header : entry(index)));
176 }
177
178 // 删除index位置的节点179 public E remove(int index) {
180 return remove(entry(index));
181 }
182
183 // 获取双向链表中指定位置的节点184 private Entry<E> entry(int index) {
185 if (index < 0 || index >= size)
186 throw new IndexOutOfBoundsException("Index: "+index+
187 ", Size: "+size);
188 Entry<E> e = header;
189 // 获取index处的节点。
190 // 若index < 双向链表长度的1/2,则从前先后查找;
191 // 否则,从后向前查找。192 if (index < (size >> 1)) {
193 for (int i = 0; i <= index; i++)
194 e = e.next;
195 } else {
196 for (int i = size; i > index; i--)
197 e = e.previous;
198 }
199 return e;
200 }
201
202 // 从前向后查找,返回“值为对象(o)的节点对应的索引”
203 // 不存在就返回-1204 public int indexOf(Object o) {
205 int index = 0;
206 if (o==null) {
207 for (Entry e = header.next; e != header; e = e.next) {
208 if (e.element==null)
209 return index;
210 index++;
211 }
212 } else {
213 for (Entry e = header.next; e != header; e = e.next) {
214 if (o.equals(e.element))
215 return index;
216 index++;
217 }
218 }
219 return -1;
220 }
221
222 // 从后向前查找,返回“值为对象(o)的节点对应的索引”
223 // 不存在就返回-1224 public int lastIndexOf(Object o) {
225 int index = size;
226 if (o==null) {
227 for (Entry e = header.previous; e != header; e = e.previous) {
228 index--;
229 if (e.element==null)
230 return index;
231 }
232 } else {
233 for (Entry e = header.previous; e != header; e = e.previous) {
234 index--;
235 if (o.equals(e.element))
236 return index;
237 }
238 }
239 return -1;
240 }
241
242 // 返回第一个节点
243 // 若LinkedList的大小为0,则返回null244 public E peek() {
245 if (size==0)
246 return null;
247 return getFirst();
248 }
249
250 // 返回第一个节点
251 // 若LinkedList的大小为0,则抛出异常252 public E element() {
253 return getFirst();
254 }
255
256 // 删除并返回第一个节点
257 // 若LinkedList的大小为0,则返回null258 public E poll() {
259 if (size==0)
260 return null;
261 return removeFirst();
262 }
263
264 // 将e添加双向链表末尾265 public boolean offer(E e) {
266 return add(e);
267 }
268
269 // 将e添加双向链表开头270 public boolean offerFirst(E e) {
271 addFirst(e);
272 return true;
273 }
274
275 // 将e添加双向链表末尾276 public boolean offerLast(E e) {
277 addLast(e);
278 return true;
279 }
280
281 // 返回第一个节点
282 // 若LinkedList的大小为0,则返回null283 public E peekFirst() {
284 if (size==0)
285 return null;
286 return getFirst();
287 }
288
289 // 返回最后一个节点
290 // 若LinkedList的大小为0,则返回null291 public E peekLast() {
292 if (size==0)
293 return null;
294 return getLast();
295 }
296
297 // 删除并返回第一个节点
298 // 若LinkedList的大小为0,则返回null299 public E pollFirst() {
300 if (size==0)
301 return null;
302 return removeFirst();
303 }
304
305 // 删除并返回最后一个节点
306 // 若LinkedList的大小为0,则返回null307 public E pollLast() {
308 if (size==0)
309 return null;
310 return removeLast();
311 }
312
313 // 将e插入到双向链表开头314 public void push(E e) {
315 addFirst(e);
316 }
317
318 // 删除并返回第一个节点319 public E pop() {
320 return removeFirst();
321 }
322
323 // 从LinkedList开始向后查找,删除第一个值为元素(o)的节点
324 // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点325 public boolean removeFirstOccurrence(Object o) {
326 return remove(o);
327 }
328
329 // 从LinkedList末尾向前查找,删除第一个值为元素(o)的节点
330 // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点331 public boolean removeLastOccurrence(Object o) {
332 if (o==null) {
333 for (Entry<E> e = header.previous; e != header; e = e.previous) {
334 if (e.element==null) {
335 remove(e);
336 return true;
337 }
338 }
339 } else {
340 for (Entry<E> e = header.previous; e != header; e = e.previous) {
341 if (o.equals(e.element)) {
342 remove(e);
343 return true;
344 }
345 }
346 }
347 return false;
348 }
349
350 // 返回“index到末尾的全部节点”对应的ListIterator对象(List迭代器)351 public ListIterator<E> listIterator(int index) {
352 return new ListItr(index);
353 }
354
355 // List迭代器356 private class ListItr implements ListIterator<E> {
357 // 上一次返回的节点358 private Entry<E> lastReturned = header;
359 // 下一个节点360 private Entry<E> next;
361 // 下一个节点对应的索引值362 private int nextIndex;
363 // 期望的改变计数。用来实现fail-fast机制。364 private int expectedModCount = modCount;
365
366 // 构造函数。
367 // 从index位置开始进行迭代368 ListItr(int index) {
369 // index的有效性处理370 if (index < 0 || index > size)
371 throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);
372 // 若 “index 小于 ‘双向链表长度的一半’”,则从第一个元素开始往后查找;
373 // 否则,从最后一个元素往前查找。374 if (index < (size >> 1)) {
375 next = header.next;
376 for (nextIndex=0; nextIndex<index; nextIndex++)
377 next = next.next;
378 } else {
379 next = header;
380 for (nextIndex=size; nextIndex>index; nextIndex--)
381 next = next.previous;
382 }
383 }
384
385 // 是否存在下一个元素386 public boolean hasNext() {
387 // 通过元素索引是否等于“双向链表大小”来判断是否达到最后。388 return nextIndex != size;
389 }
390
391 // 获取下一个元素392 public E next() {
393 checkForComodification();
394 if (nextIndex == size)
395 throw new NoSuchElementException();
396
397 lastReturned = next;
398 // next指向链表的下一个元素399 next = next.next;
400 nextIndex++;
401 return lastReturned.element;
402 }
403
404 // 是否存在上一个元素405 public boolean hasPrevious() {
406 // 通过元素索引是否等于0,来判断是否达到开头。407 return nextIndex != 0;
408 }
409
410 // 获取上一个元素411 public E previous() {
412 if (nextIndex == 0)
413 throw new NoSuchElementException();
414
415 // next指向链表的上一个元素416 lastReturned = next = next.previous;
417 nextIndex--;
418 checkForComodification();
419 return lastReturned.element;
420 }
421
422 // 获取下一个元素的索引423 public int nextIndex() {
424 return nextIndex;
425 }
426
427 // 获取上一个元素的索引428 public int previousIndex() {
429 return nextIndex-1;
430 }
431
432 // 删除当前元素。
433 // 删除双向链表中的当前节点434 public void remove() {
435 checkForComodification();
436 Entry<E> lastNext = lastReturned.next;
437 try {
438 LinkedList.this.remove(lastReturned);
439 } catch (NoSuchElementException e) {
440 throw new IllegalStateException();
441 }
442 if (next==lastReturned)
443 next = lastNext;
444 else445 nextIndex--;
446 lastReturned = header;
447 expectedModCount++;
448 }
449
450 // 设置当前节点为e451 public void set(E e) {
452 if (lastReturned == header)
453 throw new IllegalStateException();
454 checkForComodification();
455 lastReturned.element = e;
456 }
457
458 // 将e添加到当前节点的前面459 public void add(E e) {
460 checkForComodification();
461 lastReturned = header;
462 addBefore(e, next);
463 nextIndex++;
464 expectedModCount++;
465 }
466
467 // 判断 “modCount和expectedModCount是否相等”,依次来实现fail-fast机制。468 final void checkForComodification() {
469 if (modCount != expectedModCount)
470 throw new ConcurrentModificationException();
471 }
472 }
473
474 // 双向链表的节点所对应的数据结构。
475 // 包含3部分:上一节点,下一节点,当前节点值。476 private static class Entry<E> {
477 // 当前节点所包含的值478 E element;
479 // 下一个节点480 Entry<E> next;
481 // 上一个节点482 Entry<E> previous;
483
484 /**485 * 链表节点的构造函数。
486 * 参数说明:
487 * element —— 节点所包含的数据
488 * next —— 下一个节点
489 * previous —— 上一个节点
490 */491 Entry(E element, Entry<E> next, Entry<E> previous) {
492 this.element = element;
493 this.next = next;
494 this.previous = previous;
495 }
496 }
497
498 // 将节点(节点数据是e)添加到entry节点之前。499 private Entry<E> addBefore(E e, Entry<E> entry) {
500 // 新建节点newEntry,将newEntry插入到节点e之前;并且设置newEntry的数据是e501 Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
502 newEntry.previous.next = newEntry;
503 newEntry.next.previous = newEntry;
504 // 修改LinkedList大小505 size++;
506 // 修改LinkedList的修改统计数:用来实现fail-fast机制。507 modCount++;
508 return newEntry;
509 }
510
511 // 将节点从链表中删除512 private E remove(Entry<E> e) {
513 if (e == header)
514 throw new NoSuchElementException();
515
516 E result = e.element;
517 e.previous.next = e.next;
518 e.next.previous = e.previous;
519 e.next = e.previous = null;
520 e.element = null;
521 size--;
522 modCount++;
523 return result;
524 }
525
526 // 反向迭代器527 public Iterator<E> descendingIterator() {
528 return new DescendingIterator();
529 }
530
531 // 反向迭代器实现类。532 private class DescendingIterator implements Iterator {
533 final ListItr itr = new ListItr(size());
534 // 反向迭代器是否下一个元素。
535 // 实际上是判断双向链表的当前节点是否达到开头536 public boolean hasNext() {
537 return itr.hasPrevious();
538 }
539 // 反向迭代器获取下一个元素。
540 // 实际上是获取双向链表的前一个节点541 public E next() {
542 return itr.previous();
543 }
544 // 删除当前节点545 public void remove() {
546 itr.remove();
547 }
548 }
549
550
551 // 返回LinkedList的Object[]数组552 public Object[] toArray() {
553 // 新建Object[]数组554 Object[] result = new Object[size];
555 int i = 0;
556 // 将链表中所有节点的数据都添加到Object[]数组中557 for (Entry<E> e = header.next; e != header; e = e.next)
558 result[i++] = e.element;
559 return result;
560 }
561
562 // 返回LinkedList的模板数组。所谓模板数组,即可以将T设为任意的数据类型563 public <T> T[] toArray(T[] a) {
564 // 若数组a的大小 < LinkedList的元素个数(意味着数组a不能容纳LinkedList中全部元素)
565 // 则新建一个T[]数组,T[]的大小为LinkedList大小,并将该T[]赋值给a。566 if (a.length < size)
567 a = (T[])java.lang.reflect.Array.newInstance(
568 a.getClass().getComponentType(), size);
569 // 将链表中所有节点的数据都添加到数组a中570 int i = 0;
571 Object[] result = a;
572 for (Entry<E> e = header.next; e != header; e = e.next)
573 result[i++] = e.element;
574
575 if (a.length > size)
576 a[size] = null;
577
578 return a;
579 }
580
581
582 // 克隆函数。返回LinkedList的克隆对象。583 public Object clone() {
584 LinkedList<E> clone = null;
585 // 克隆一个LinkedList克隆对象586 try {
587 clone = (LinkedList<E>) super.clone();
588 } catch (CloneNotSupportedException e) {
589 throw new InternalError();
590 }
591
592 // 新建LinkedList表头节点593 clone.header = new Entry<E>(null, null, null);
594 clone.header.next = clone.header.previous = clone.header;
595 clone.size = 0;
596 clone.modCount = 0;
597
598 // 将链表中所有节点的数据都添加到克隆对象中599 for (Entry<E> e = header.next; e != header; e = e.next)
600 clone.add(e.element);
601
602 return clone;
603 }
604
605 // java.io.Serializable的写入函数
606 // 将LinkedList的“容量,所有的元素值”都写入到输出流中607 private void writeObject(java.io.ObjectOutputStream s)
608 throws java.io.IOException {
609 // Write out any hidden serialization magic610 s.defaultWriteObject();
611
612 // 写入“容量”613 s.writeInt(size);
614
615 // 将链表中所有节点的数据都写入到输出流中616 for (Entry e = header.next; e != header; e = e.next)
617 s.writeObject(e.element);
618 }
619
620 // java.io.Serializable的读取函数:根据写入方式反向读出
621 // 先将LinkedList的“容量”读出,然后将“所有的元素值”读出622 private void readObject(java.io.ObjectInputStream s)
623 throws java.io.IOException, ClassNotFoundException {
624 // Read in any hidden serialization magic625 s.defaultReadObject();
626
627 // 从输入流中读取“容量”628 int size = s.readInt();
629
630 // 新建链表表头节点631 header = new Entry<E>(null, null, null);
632 header.next = header.previous = header;
633
634 // 从输入流中将“所有的元素值”并逐个添加到链表中635 for (int i=0; i<size; i++)
636 addBefore((E)s.readObject(), header);
637 }
638
639 }
下面是英文版的源码
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.util.function.Consumer;
/**
* Doubly-linked list implementation of the {@code List} and {@code Deque}
* interfaces. Implements all optional list operations, and permits all
* elements (including {@code null}).
*
* <p>All of the operations perform as could be expected for a doubly-linked
* list. Operations that index into the list will traverse the list from
* the beginning or the end, whichever is closer to the specified index.
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access a linked list concurrently, and at least
* one of the threads modifies the list structurally, it <i>must</i> be
* synchronized externally. (A structural modification is any operation
* that adds or deletes one or more elements; merely setting the value of
* an element is not a structural modification.) This is typically
* accomplished by synchronizing on some object that naturally
* encapsulates the list.
*
* If no such object exists, the list should be "wrapped" using the
* {@link Collections#synchronizedList Collections.synchronizedList}
* method. This is best done at creation time, to prevent accidental
* unsynchronized access to the list:<pre>
* List list = Collections.synchronizedList(new LinkedList(...));</pre>
*
* <p>The iterators returned by this class's {@code iterator} and
* {@code listIterator} methods are <i>fail-fast</i>: if the list is
* structurally modified at any time after the iterator is created, in
* any way except through the Iterator's own {@code remove} or
* {@code add} methods, the iterator will throw a {@link
* ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than
* risking arbitrary, non-deterministic behavior at an undetermined
* time in the future.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw {@code ConcurrentModificationException} on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* <p>This class is a member of the
* <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @author Josh Bloch
* @see List
* @see ArrayList
* @since 1.2
* @param <E> the type of elements held in this collection
*/
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;
/**
* 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;
/**
* Constructs an empty list.
*/
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* 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++;
}
/**
* Unlinks non-null first node f.
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* Unlinks non-null last node l.
*/
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
/**
* Unlinks non-null node x.
*/
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Removes and returns the last element from this list.
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}
/**
* Returns {@code true} if this list contains the specified element.
* More formally, returns {@code true} if and only if this list contains
* at least one element {@code e} such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return {@code true} if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator. The behavior of this operation is undefined if
* the specified collection is modified while the operation is in
* progress. (Note that this will occur if the specified collection is
* this list, and it's nonempty.)
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element
* from the specified collection
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
// Positional Access Operations
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(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;
}
}
// Search Operations
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
// Queue operations.
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E element() {
return getFirst();
}
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E remove() {
return removeFirst();
}
/**
* Adds the specified element as the tail (last element) of this list.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
* @since 1.5
*/
public boolean offer(E e) {
return add(e);
}
// Deque operations
/**
* Inserts the specified element at the front of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @since 1.6
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* Inserts the specified element at the end of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerLast})
* @since 1.6
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
public E pop() {
return removeFirst();
}
/**
* Removes the first occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
/**
* Removes the last occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* Returns a list-iterator of the elements in this list (in proper
* sequence), starting at the specified position in the list.
* Obeys the general contract of {@code List.listIterator(int)}.<p>
*
* The list-iterator is <i>fail-fast</i>: if the list is structurally
* modified at any time after the Iterator is created, in any way except
* through the list-iterator's own {@code remove} or {@code add}
* methods, the list-iterator will throw a
* {@code ConcurrentModificationException}. Thus, in the face of
* concurrent modification, the iterator fails quickly and cleanly, rather
* than risking arbitrary, non-deterministic behavior at an undetermined
* time in the future.
*
* @param index index of the first element to be returned from the
* list-iterator (by a call to {@code next})
* @return a ListIterator of the elements in this list (in proper
* sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see List#listIterator(int)
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
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;
}
}
/**
* @since 1.6
*/
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
/**
* Adapter to provide descending iterators via ListItr.previous
*/
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* Returns a shallow copy of this {@code LinkedList}. (The elements
* themselves are not cloned.)
*
* @return a shallow copy of this {@code LinkedList} instance
*/
public Object clone() {
LinkedList<E> clone = superClone();
// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list
* in proper sequence
*/
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
/**
* Returns an array containing all of the elements in this list in
* proper sequence (from first to last element); the runtime type of
* the returned array is that of the specified array. If the list fits
* in the specified array, it is returned therein. Otherwise, a new
* array is allocated with the runtime type of the specified array and
* the size of this list.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to {@code null}.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any null elements.)
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose {@code x} is a list known to contain only strings.
* The following code can be used to dump the list into a newly
* allocated array of {@code String}:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
private static final long serialVersionUID = 876323262645176354L;
/**
* Saves the state of this {@code LinkedList} instance to a stream
* (that is, serializes it).
*
* @serialData The size of the list (the number of elements it
* contains) is emitted (int), followed by all of its
* elements (each an Object) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(size);
// Write out all elements in the proper order.
for (Node<E> x = first; x != null; x = x.next)
s.writeObject(x.item);
}
/**
* Reconstitutes this {@code LinkedList} instance from a stream
* (that is, deserializes it).
*/
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}
/**
* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* list.
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
* {@link Spliterator#ORDERED}. Overriding implementations should document
* the reporting of additional characteristic values.
*
* @implNote
* The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}
* and implements {@code trySplit} to permit limited parallelism..
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new LLSpliterator<E>(this, -1, 0);
}
/** A customized variant of Spliterators.IteratorSpliterator */
static final class LLSpliterator<E> implements Spliterator<E> {
static final int BATCH_UNIT = 1 << 10; // batch array size increment
static final int MAX_BATCH = 1 << 25; // max batch array size;
final LinkedList<E> list; // null OK unless traversed
Node<E> current; // current node; null until initialized
int est; // size estimate; -1 until first needed
int expectedModCount; // initialized when est set
int batch; // batch size for splits
LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
this.list = list;
this.est = est;
this.expectedModCount = expectedModCount;
}
final int getEst() {
int s; // force initialization
final LinkedList<E> lst;
if ((s = est) < 0) {
if ((lst = list) == null)
s = est = 0;
else {
expectedModCount = lst.modCount;
current = lst.first;
s = est = lst.size;
}
}
return s;
}
public long estimateSize() { return (long) getEst(); }
public Spliterator<E> trySplit() {
Node<E> p;
int s = getEst();
if (s > 1 && (p = current) != null) {
int n = batch + BATCH_UNIT;
if (n > s)
n = s;
if (n > MAX_BATCH)
n = MAX_BATCH;
Object[] a = new Object[n];
int j = 0;
do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
current = p;
batch = j;
est = s - j;
return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
}
return null;
}
public void forEachRemaining(Consumer<? super E> action) {
Node<E> p; int n;
if (action == null) throw new NullPointerException();
if ((n = getEst()) > 0 && (p = current) != null) {
current = null;
est = 0;
do {
E e = p.item;
p = p.next;
action.accept(e);
} while (p != null && --n > 0);
}
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public boolean tryAdvance(Consumer<? super E> action) {
Node<E> p;
if (action == null) throw new NullPointerException();
if (getEst() > 0 && (p = current) != null) {
--est;
E e = p.item;
current = p.next;
action.accept(e);
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
}