4.Java集合框架剖析 之 LinkedList源码剖析

时间:2020-12-21 17:52:34
  1 package java.util;
  2 
  3 import java.util.function.Consumer;
  4 
  5 //LinkedList基于链表实现
  6 //实现了List、Deque、Cloneable、Serializable接口
  7 public class LinkedList<E> extends AbstractSequentialList<E>
  8     implements List<E>, Deque<E>, Cloneable, java.io.Serializable {
  9     //list链表的长度
 10     transient int size = 0; 
 11 
 12     //list链表的第一个结点
 13     transient Node<E> first;
 14 
 15     //list链表的最后一个结点
 16     transient Node<E> last;
 17 
 18     ////list链表的无参构造方法,什么事情都不做
 19     public LinkedList() {
 20     }
 21 
 22     //把一个集合中的元素加到list链表中
 23     public LinkedList(Collection<? extends E> c) {
 24         this();
 25         addAll(c);
 26     }
 27 
 28     //私有方法,在list链表的开始连接一个节点
 29     private void linkFirst(E e) {
 30         final Node<E> f = first;
 31         final Node<E> newNode = new Node<>(null, e, f);
 32         first = newNode;
 33         if (f == null)
 34             last = newNode;
 35         else
 36             f.prev = newNode;
 37         size++;
 38         modCount++;
 39     }
 40 
 41     //在list链表的末尾连接一个节点
 42     void linkLast(E e) {
 43         final Node<E> l = last;
 44         final Node<E> newNode = new Node<>(l, e, null);
 45         last = newNode;
 46         if (l == null)
 47             first = newNode;
 48         else
 49             l.next = newNode;
 50         size++;
 51         modCount++;
 52     }
 53 
 54     //在节点succ之前连接一个节点
 55     void linkBefore(E e, Node<E> succ) {
 56         // assert succ != null;
 57         final Node<E> pred = succ.prev;
 58         final Node<E> newNode = new Node<>(pred, e, succ);
 59         succ.prev = newNode;
 60         if (pred == null)
 61             first = newNode;
 62         else
 63             pred.next = newNode;
 64         size++;
 65         modCount++;
 66     }
 67 
 68     //释放(删除)第一个节点,私有方法,其他地方调用
 69     private E unlinkFirst(Node<E> f) {
 70         // assert f == first && f != null;
 71         final E element = f.item;
 72         final Node<E> next = f.next;
 73         f.item = null;
 74         f.next = null; // help GC
 75         first = next;
 76         if (next == null)
 77             last = null;
 78         else
 79             next.prev = null;
 80         size--;
 81         modCount++;
 82         return element;
 83     }
 84 
 85     //释放(删除)最后一个节点,私有方法,其他地方调用
 86     private E unlinkLast(Node<E> l) {
 87         // assert l == last && l != null;
 88         final E element = l.item;
 89         final Node<E> prev = l.prev;
 90         l.item = null;
 91         l.prev = null; // help GC
 92         last = prev;
 93         if (prev == null)
 94             first = null;
 95         else
 96             prev.next = null;
 97         size--;
 98         modCount++;
 99         return element;
100     }
101 
102     //释放(删除)节点,其他地方调用
103     E unlink(Node<E> x) {
104         // assert x != null;
105         final E element = x.item;
106         final Node<E> next = x.next;//x节点后面的节点
107         final Node<E> prev = x.prev;//x节点前面的节点
108 
109         if (prev == null) {
110             first = next;
111         } else {
112             prev.next = next;
113             x.prev = null;
114         }
115 
116         if (next == null) {
117             last = prev;
118         } else {
119             next.prev = prev;
120             x.next = null;
121         }
122 
123         x.item = null;
124         size--;
125         modCount++;
126         return element;
127     }
128 
129     //返回列表首节点元素值
130     public E getFirst() {
131         final Node<E> f = first;
132         if (f == null)
133             throw new NoSuchElementException();
134         return f.item;
135     }
136 
137     //返回列表最后一个节点元素值
138     public E getLast() {
139         final Node<E> l = last;
140         if (l == null)
141             throw new NoSuchElementException();
142         return l.item;
143     }
144 
145     //删除第一个节点,调用私有方法unlinkFirst()
146     public E removeFirst() {
147         final Node<E> f = first;
148         if (f == null)
149             throw new NoSuchElementException();
150         return unlinkFirst(f);
151     }
152 
153     //删除最后一个节点,调用私有方法removeLast()
154     public E removeLast() {
155         final Node<E> l = last;
156         if (l == null)
157             throw new NoSuchElementException();
158         return unlinkLast(l);
159     }
160 
161     //在列表头插入节点e
162     public void addFirst(E e) {
163         linkFirst(e);
164     }
165 
166     //在列表尾插入节点e
167     public void addLast(E e) {
168         linkLast(e);
169     }
170 
171     //判断列表中是否包含有元素o
172     public boolean contains(Object o) {
173         return indexOf(o) != -1;
174     }
175 
176     /列表长度大小
177     public int size() {
178         return size;
179     }
180 
181     /增加一个元素,(在列尾增加一个元素)
182     public boolean add(E e) {
183         linkLast(e);
184         return true;
185     }
186 
187     //删除指定的节点元素
188     public boolean remove(Object o) {
189         if (o == null) {
190             for (Node<E> x = first; x != null; x = x.next) {
191                 if (x.item == null) {
192                     unlink(x);
193                     return true;
194                 }
195             }
196         } else {
197             for (Node<E> x = first; x != null; x = x.next) {
198                 if (o.equals(x.item)) {
199                     unlink(x);
200                     return true;
201                 }
202             }
203         }
204         return false;
205     }
206 
207     //将集合c中的所有元素插入到列尾
208     public boolean addAll(Collection<? extends E> c) {
209         return addAll(size, c);
210     }
211 
212     //将集合c中的所有元素插入到指定位置index
213     public boolean addAll(int index, Collection<? extends E> c) {
214         checkPositionIndex(index);
215 
216         Object[] a = c.toArray();
217         int numNew = a.length;
218         if (numNew == 0)
219             return false;
220 
221         Node<E> pred, succ;
222         if (index == size) {
223             succ = null;
224             pred = last;
225         } else {
226             succ = node(index);
227             pred = succ.prev;
228         }
229 
230         for (Object o : a) {
231             @SuppressWarnings("unchecked") E e = (E) o;
232             Node<E> newNode = new Node<>(pred, e, null);
233             if (pred == null)
234                 first = newNode;
235             else
236                 pred.next = newNode;
237             pred = newNode;
238         }
239 
240         if (succ == null) {
241             last = pred;
242         } else {
243             pred.next = succ;
244             succ.prev = pred;
245         }
246 
247         size += numNew;
248         modCount++;
249         return true;
250     }
251 
252     //删除列表中所有节点
253     public void clear() {
254         for (Node<E> x = first; x != null; ) {
255             Node<E> next = x.next;
256             x.item = null;
257             x.next = null;
258             x.prev = null;
259             x = next;
260         }
261         first = last = null;
262         size = 0;
263         modCount++;
264     }
265 
266     //获取指定索引位置节点的元素值
267     public E get(int index) {
268         checkElementIndex(index);
269         return node(index).item;
270     }
271 
272     //替换指定索引位置节点的元素值
273     public E set(int index, E element) {
274         checkElementIndex(index);
275         Node<E> x = node(index);
276         E oldVal = x.item;
277         x.item = element;
278         return oldVal;
279     }
280 
281     //在指定索引位置之前插入元素e
282     public void add(int index, E element) {
283         checkPositionIndex(index);
284 
285         if (index == size)
286             linkLast(element);
287         else
288             linkBefore(element, node(index));
289     }
290 
291     //删除指定位置的元素
292     public E remove(int index) {
293         checkElementIndex(index);
294         return unlink(node(index));
295     }
296 
297     //判断指定索引位置的元素是否存在
298     private boolean isElementIndex(int index) {
299         return index >= 0 && index < size;
300     }
301 
302     private boolean isPositionIndex(int index) {
303         return index >= 0 && index <= size;
304     }
305 
306     //构建 IndexOutOfBoundsException详细信息
307     private String outOfBoundsMsg(int index) {
308         return "Index: "+index+", Size: "+size;
309     }
310 
311     private void checkElementIndex(int index) {
312         if (!isElementIndex(index))
313             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
314     }
315 
316     private void checkPositionIndex(int index) {
317         if (!isPositionIndex(index))
318             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
319     }
320 
321     //返回指定索引位置的节点(二分查找)
322     Node<E> node(int index) {
323         //当index<size/2时,从列表前半部分开始,否则从后半部分开
324         if (index < (size >> 1)) {
325             Node<E> x = first;
326             for (int i = 0; i < index; i++)
327                 x = x.next;
328             return x;
329         } else {
330             Node<E> x = last;
331             for (int i = size - 1; i > index; i--)
332                 x = x.prev;
333             return x;
334         }
335     }
336  
337     //返回列表中第一次出现o的位置,若不存在则返回-
338     public int indexOf(Object o) {
339         int index = 0;
340         if (o == null) {
341             for (Node<E> x = first; x != null; x = x.next) {
342                 if (x.item == null)
343                     return index;
344                 index++;
345             }
346         } else {
347             for (Node<E> x = first; x != null; x = x.next) {
348                 if (o.equals(x.item))
349                     return index;
350                 index++;
351             }
352         }
353         return -1;
354     }
355 
356     //逆向搜索,返回第一出现o的位置,不存在则返回-1
357     public int lastIndexOf(Object o) {
358         int index = size;
359         if (o == null) {
360             for (Node<E> x = last; x != null; x = x.prev) {
361                 index--;
362                 if (x.item == null)
363                     return index;
364             }
365         } else {
366             for (Node<E> x = last; x != null; x = x.prev) {
367                 index--;
368                 if (o.equals(x.item))
369                     return index;
370             }
371         }
372         return -1;
373     }
374 
375     // Queue操作
376     //获取列表首节点元素值
377     public E peek() {
378         final Node<E> f = first;
379         return (f == null) ? null : f.item;
380     }
381 
382     //获取列表首节点元素值,若为空则抛异常
383     public E element() {
384         return getFirst();
385     }
386 
387    //检索首节点,若空则返回null,不为空则返回其元素值并删除首节点
388     public E poll() {
389         final Node<E> f = first;
390         return (f == null) ? null : unlinkFirst(f);
391     }
392 
393     //检索首节点,若空则抛异常,不为空则返回其元素值并删除首节点
394     public E remove() {
395         return removeFirst();
396     }
397 
398     //在列表尾部增加节点e
399     public boolean offer(E e) {
400         return add(e);
401     }
402 
403     // Deque操作
404     
405     //在列表首部插入节点e
406     public boolean offerFirst(E e) {
407         addFirst(e);
408         return true;
409     }
410 
411       //在列表尾部插入节点e
412     public boolean offerLast(E e) {
413         addLast(e);
414         return true;
415     }
416 
417     public E peekFirst() {
418         final Node<E> f = first;
419         return (f == null) ? null : f.item;
420      }
421 
422       //获取列表尾节点元素值
423     public E peekLast() {
424         final Node<E> l = last;
425         return (l == null) ? null : l.item;
426     }
427 
428     public E pollFirst() {
429         final Node<E> f = first;
430         return (f == null) ? null : unlinkFirst(f);
431     }
432 
433     public E pollLast() {
434         final Node<E> l = last;
435         return (l == null) ? null : unlinkLast(l);
436     }
437 
438     public void push(E e) {
439         addFirst(e);
440     }
441 
442     public E pop() {
443         return removeFirst();
444     }
445 
446     public boolean removeFirstOccurrence(Object o) {
447         return remove(o);
448     }
449 
450     public boolean removeLastOccurrence(Object o) {
451         if (o == null) {
452             for (Node<E> x = last; x != null; x = x.prev) {
453                 if (x.item == null) {
454                     unlink(x);
455                     return true;
456                 }
457             }
458         } else {
459             for (Node<E> x = last; x != null; x = x.prev) {
460                 if (o.equals(x.item)) {
461                     unlink(x);
462                     return true;
463                 }
464             }
465         }
466         return false;
467     }
468 
469     public ListIterator<E> listIterator(int index) {
470         checkPositionIndex(index);
471         return new ListItr(index);
472     }
473 
474     private class ListItr implements ListIterator<E> {
475         private Node<E> lastReturned;
476         private Node<E> next;
477         private int nextIndex;
478         private int expectedModCount = modCount;
479 
480         ListItr(int index) {
481             // assert isPositionIndex(index);
482             next = (index == size) ? null : node(index);
483             nextIndex = index;
484         }
485 
486         public boolean hasNext() {
487             return nextIndex < size;
488         }
489 
490         public E next() {
491             checkForComodification();
492             if (!hasNext())
493                 throw new NoSuchElementException();
494 
495             lastReturned = next;
496             next = next.next;
497             nextIndex++;
498             return lastReturned.item;
499         }
500 
501         public boolean hasPrevious() {
502             return nextIndex > 0;
503         }
504 
505         public E previous() {
506             checkForComodification();
507             if (!hasPrevious())
508                 throw new NoSuchElementException();
509 
510             lastReturned = next = (next == null) ? last : next.prev;
511             nextIndex--;
512             return lastReturned.item;
513         }
514 
515         public int nextIndex() {
516             return nextIndex;
517         }
518 
519         public int previousIndex() {
520             return nextIndex - 1;
521         }
522 
523         public void remove() {
524             checkForComodification();
525             if (lastReturned == null)
526                 throw new IllegalStateException();
527 
528             Node<E> lastNext = lastReturned.next;
529             unlink(lastReturned);
530             if (next == lastReturned)
531                 next = lastNext;
532             else
533                 nextIndex--;
534             lastReturned = null;
535             expectedModCount++;
536         }
537 
538         public void set(E e) {
539             if (lastReturned == null)
540                 throw new IllegalStateException();
541             checkForComodification();
542             lastReturned.item = e;
543         }
544 
545         public void add(E e) {
546             checkForComodification();
547             lastReturned = null;
548             if (next == null)
549                 linkLast(e);
550             else
551                 linkBefore(e, next);
552             nextIndex++;
553             expectedModCount++;
554         }
555 
556         public void forEachRemaining(Consumer<? super E> action) {
557             Objects.requireNonNull(action);
558             while (modCount == expectedModCount && nextIndex < size) {
559                 action.accept(next.item);
560                 lastReturned = next;
561                 next = next.next;
562                 nextIndex++;
563             }
564             checkForComodification();
565         }
566 
567         final void checkForComodification() {
568             if (modCount != expectedModCount)
569                 throw new ConcurrentModificationException();
570         }
571     }
572 
573     private static class Node<E> {
574         E item;
575         Node<E> next;
576         Node<E> prev;
577 
578         Node(Node<E> prev, E element, Node<E> next) {
579             this.item = element;
580             this.next = next;
581             this.prev = prev;
582         }
583     }
584 
585     public Iterator<E> descendingIterator() {
586         return new DescendingIterator();
587     }
588 
589     private class DescendingIterator implements Iterator<E> {
590         private final ListItr itr = new ListItr(size());
591         public boolean hasNext() {
592             return itr.hasPrevious();
593         }
594         public E next() {
595             return itr.previous();
596         }
597         public void remove() {
598             itr.remove();
599         }
600     }
601 
602     @SuppressWarnings("unchecked")
603     private LinkedList<E> superClone() {
604         try {
605             return (LinkedList<E>) super.clone();
606         } catch (CloneNotSupportedException e) {
607             throw new InternalError(e);
608         }
609     }
610 
611     public Object clone() {
612         LinkedList<E> clone = superClone();
613         clone.first = clone.last = null;
614         clone.size = 0;
615         clone.modCount = 0;
616 
617         for (Node<E> x = first; x != null; x = x.next)
618             clone.add(x.item);
619 
620         return clone;
621     }
622 
623     public Object[] toArray() {
624         Object[] result = new Object[size];
625         int i = 0;
626         for (Node<E> x = first; x != null; x = x.next)
627             result[i++] = x.item;
628         return result;
629     }
630 
631     @SuppressWarnings("unchecked")
632     public <T> T[] toArray(T[] a) {
633         if (a.length < size)
634             a = (T[])java.lang.reflect.Array.newInstance(
635                                 a.getClass().getComponentType(), size);
636         int i = 0;
637         Object[] result = a;
638         for (Node<E> x = first; x != null; x = x.next)
639             result[i++] = x.item;
640 
641         if (a.length > size)
642             a[size] = null;
643 
644         return a;
645     }
646 
647     private static final long serialVersionUID = 876323262645176354L;
648 
649     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
650         s.defaultWriteObject();
651 
652         s.writeInt(size);
653 
654         for (Node<E> x = first; x != null; x = x.next)
655             s.writeObject(x.item);
656     }
657 
658     @SuppressWarnings("unchecked")
659     private void readObject(java.io.ObjectInputStream s)
660         throws java.io.IOException, ClassNotFoundException {
661         s.defaultReadObject();
662         int size = s.readInt();
663         for (int i = 0; i < size; i++)
664             linkLast((E)s.readObject());
665     }
666 
667     @Override
668     public Spliterator<E> spliterator() {
669         return new LLSpliterator<E>(this, -1, 0);
670     }
671 
672     static final class LLSpliterator<E> implements Spliterator<E> {
673         static final int BATCH_UNIT = 1 << 10;  // batch array size increment
674         static final int MAX_BATCH = 1 << 25;  // max batch array size;
675         final LinkedList<E> list; // null OK unless traversed
676         Node<E> current;      // current node; null until initialized
677         int est;              // size estimate; -1 until first needed
678         int expectedModCount; // initialized when est set
679         int batch;            // batch size for splits
680 
681         LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
682             this.list = list;
683             this.est = est;
684             this.expectedModCount = expectedModCount;
685         }
686 
687         final int getEst() {
688             int s; // force initialization
689             final LinkedList<E> lst;
690             if ((s = est) < 0) {
691                 if ((lst = list) == null)
692                     s = est = 0;
693                 else {
694                     expectedModCount = lst.modCount;
695                     current = lst.first;
696                     s = est = lst.size;
697                 }
698             }
699             return s;
700         }
701 
702         public long estimateSize() { return (long) getEst(); }
703 
704         public Spliterator<E> trySplit() {
705             Node<E> p;
706             int s = getEst();
707             if (s > 1 && (p = current) != null) {
708                 int n = batch + BATCH_UNIT;
709                 if (n > s)
710                     n = s;
711                 if (n > MAX_BATCH)
712                     n = MAX_BATCH;
713                 Object[] a = new Object[n];
714                 int j = 0;
715                 do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
716                 current = p;
717                 batch = j;
718                 est = s - j;
719                 return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
720             }
721             return null;
722         }
723 
724         public void forEachRemaining(Consumer<? super E> action) {
725             Node<E> p; int n;
726             if (action == null) throw new NullPointerException();
727             if ((n = getEst()) > 0 && (p = current) != null) {
728                 current = null;
729                 est = 0;
730                 do {
731                     E e = p.item;
732                     p = p.next;
733                     action.accept(e);
734                 } while (p != null && --n > 0);
735             }
736             if (list.modCount != expectedModCount)
737                 throw new ConcurrentModificationException();
738         }
739 
740         public boolean tryAdvance(Consumer<? super E> action) {
741             Node<E> p;
742             if (action == null) throw new NullPointerException();
743             if (getEst() > 0 && (p = current) != null) {
744                 --est;
745                 E e = p.item;
746                 current = p.next;
747                 action.accept(e);
748                 if (list.modCount != expectedModCount)
749                     throw new ConcurrentModificationException();
750                 return true;
751             }
752             return false;
753         }
754 
755         public int characteristics() {
756             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
757         }
758     }
759 }