LinkedList

  1. /* 
  2.  * @(#)LinkedList.java  1.67 06/04/21 
  3.  * 
  4.  * Copyright 2006 Sun Microsystems, Inc. All rights reserved. 
  5.  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 
  6.  */  
  7. package java.util;  
  8. /** 
  9.  * Linked list implementation of the <tt>List</tt> interface.  Implements all 
  10.  * optional list operations, and permits all elements (including 
  11.  * <tt>null</tt>).  In addition to implementing the <tt>List</tt> interface, 
  12.  * the <tt>LinkedList</tt> class provides uniformly named methods to 
  13.  * <tt>get</tt>, <tt>remove</tt> and <tt>insert</tt> an element at the 
  14.  * beginning and end of the list.  These operations allow linked lists to be 
  15.  * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque 
  16.  * double-ended queue}. <p> 
  17.  * 
  18.  * The class implements the <tt>Deque</tt> interface, providing 
  19.  * first-in-first-out queue operations for <tt>add</tt>, 
  20.  * <tt>poll</tt>, along with other stack and deque operations.<p> 
  21.  * 
  22.  * All of the operations perform as could be expected for a doubly-linked 
  23.  * list.  Operations that index into the list will traverse the list from 
  24.  * the beginning or the end, whichever is closer to the specified index.<p> 
  25.  * 
  26.  * <p><strong>Note that this implementation is not synchronized.</strong> 
  27.  * If multiple threads access a linked list concurrently, and at least 
  28.  * one of the threads modifies the list structurally, it <i>must</i> be 
  29.  * synchronized externally.  (A structural modification is any operation 
  30.  * that adds or deletes one or more elements; merely setting the value of 
  31.  * an element is not a structural modification.)  This is typically 
  32.  * accomplished by synchronizing on some object that naturally 
  33.  * encapsulates the list. 
  34.  * 
  35.  * If no such object exists, the list should be "wrapped" using the 
  36.  * {@link Collections#synchronizedList Collections.synchronizedList} 
  37.  * method.  This is best done at creation time, to prevent accidental 
  38.  * unsynchronized access to the list:<pre> 
  39.  *   List list = Collections.synchronizedList(new LinkedList(...));</pre> 
  40.  * 
  41.  * <p>The iterators returned by this class's <tt>iterator</tt> and 
  42.  * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is 
  43.  * structurally modified at any time after the iterator is created, in 
  44.  * any way except through the Iterator's own <tt>remove</tt> or 
  45.  * <tt>add</tt> methods, the iterator will throw a {@link 
  46.  * ConcurrentModificationException}.  Thus, in the face of concurrent 
  47.  * modification, the iterator fails quickly and cleanly, rather than 
  48.  * risking arbitrary, non-deterministic behavior at an undetermined 
  49.  * time in the future. 
  50.  * 
  51.  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed 
  52.  * as it is, generally speaking, impossible to make any hard guarantees in the 
  53.  * presence of unsynchronized concurrent modification.  Fail-fast iterators 
  54.  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. 
  55.  * Therefore, it would be wrong to write a program that depended on this 
  56.  * exception for its correctness:   <i>the fail-fast behavior of iterators 
  57.  * should be used only to detect bugs.</i> 
  58.  * 
  59.  * <p>This class is a member of the 
  60.  * <a href="{@docRoot}/../technotes/guides/collections/index.html" mce_href="technotes/guides/collections/index.html"> 
  61.  * Java Collections Framework</a>. 
  62.  * 
  63.  * @author  Josh Bloch 
  64.  * @version 1.67, 04/21/06 
  65.  * @see     List 
  66.  * @see     ArrayList 
  67.  * @see     Vector 
  68.  * @since 1.2 
  69.  * @param <E> the type of elements held in this collection 
  70.  */  
  71. public class LinkedList<E>  
  72.     extends AbstractSequentialList<E>  
  73.     implements List<E>, Deque<E>, Cloneable, java.io.Serializable  
  74. {  
  75.     private transient Entry<E> header = new Entry<E>(nullnullnull);  
  76.     private transient int size = 0;  
  77.     /** 
  78.      * Constructs an empty list. 
  79.      */  
  80.     public LinkedList() {  
  81.         header.next = header.previous = header;  
  82.     }  
  83.     /** 
  84.      * Constructs a list containing the elements of the specified 
  85.      * collection, in the order they are returned by the collection's 
  86.      * iterator. 
  87.      * 
  88.      * @param  c the collection whose elements are to be placed into this list 
  89.      * @throws NullPointerException if the specified collection is null 
  90.      */  
  91.     public LinkedList(Collection<? extends E> c) {  
  92.     this();  
  93.     addAll(c);  
  94.     }  
  95.     /** 
  96.      * Returns the first element in this list. 
  97.      * 
  98.      * @return the first element in this list 
  99.      * @throws NoSuchElementException if this list is empty 
  100.      */  
  101.     public E getFirst() {  
  102.     if (size==0)  
  103.         throw new NoSuchElementException();  
  104.     return header.next.element;  
  105.     }  
  106.     /** 
  107.      * Returns the last element in this list. 
  108.      * 
  109.      * @return the last element in this list 
  110.      * @throws NoSuchElementException if this list is empty 
  111.      */  
  112.     public E getLast()  {  
  113.     if (size==0)  
  114.         throw new NoSuchElementException();  
  115.     return header.previous.element;  
  116.     }  
  117.     /** 
  118.      * Removes and returns the first element from this list. 
  119.      * 
  120.      * @return the first element from this list 
  121.      * @throws NoSuchElementException if this list is empty 
  122.      */  
  123.     public E removeFirst() {  
  124.     return remove(header.next);  
  125.     }  
  126.     /** 
  127.      * Removes and returns the last element from this list. 
  128.      * 
  129.      * @return the last element from this list 
  130.      * @throws NoSuchElementException if this list is empty 
  131.      */  
  132.     public E removeLast() {  
  133.     return remove(header.previous);  
  134.     }  
  135.     /** 
  136.      * Inserts the specified element at the beginning of this list. 
  137.      * 
  138.      * @param e the element to add 
  139.      */  
  140.     public void addFirst(E e) {  
  141.     addBefore(e, header.next);  
  142.     }  
  143.     /** 
  144.      * Appends the specified element to the end of this list. 
  145.      * 
  146.      * <p>This method is equivalent to {@link #add}. 
  147.      * 
  148.      * @param e the element to add 
  149.      */  
  150.     public void addLast(E e) {  
  151.     addBefore(e, header);  
  152.     }  
  153.     /** 
  154.      * Returns <tt>true</tt> if this list contains the specified element. 
  155.      * More formally, returns <tt>true</tt> if and only if this list contains 
  156.      * at least one element <tt>e</tt> such that 
  157.      * <tt>(o==null ? e==null : o.equals(e))</tt>. 
  158.      * 
  159.      * @param o element whose presence in this list is to be tested 
  160.      * @return <tt>true</tt> if this list contains the specified element 
  161.      */  
  162.     public boolean contains(Object o) {  
  163.         return indexOf(o) != -1;  
  164.     }  
  165.     /** 
  166.      * Returns the number of elements in this list. 
  167.      * 
  168.      * @return the number of elements in this list 
  169.      */  
  170.     public int size() {  
  171.     return size;  
  172.     }  
  173.     /** 
  174.      * Appends the specified element to the end of this list. 
  175.      * 
  176.      * <p>This method is equivalent to {@link #addLast}. 
  177.      * 
  178.      * @param e element to be appended to this list 
  179.      * @return <tt>true</tt> (as specified by {@link Collection#add}) 
  180.      */  
  181.     public boolean add(E e) {  
  182.     addBefore(e, header);  
  183.         return true;  
  184.     }  
  185.     /** 
  186.      * Removes the first occurrence of the specified element from this list, 
  187.      * if it is present.  If this list does not contain the element, it is 
  188.      * unchanged.  More formally, removes the element with the lowest index 
  189.      * <tt>i</tt> such that 
  190.      * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> 
  191.      * (if such an element exists).  Returns <tt>true</tt> if this list 
  192.      * contained the specified element (or equivalently, if this list 
  193.      * changed as a result of the call). 
  194.      * 
  195.      * @param o element to be removed from this list, if present 
  196.      * @return <tt>true</tt> if this list contained the specified element 
  197.      */  
  198.     public boolean remove(Object o) {  
  199.         if (o==null) {  
  200.             for (Entry<E> e = header.next; e != header; e = e.next) {  
  201.                 if (e.element==null) {  
  202.                     remove(e);  
  203.                     return true;  
  204.                 }  
  205.             }  
  206.         } else {  
  207.             for (Entry<E> e = header.next; e != header; e = e.next) {  
  208.                 if (o.equals(e.element)) {  
  209.                     remove(e);  
  210.                     return true;  
  211.                 }  
  212.             }  
  213.         }  
  214.         return false;  
  215.     }  
  216.     /** 
  217.      * Appends all of the elements in the specified collection to the end of 
  218.      * this list, in the order that they are returned by the specified 
  219.      * collection's iterator.  The behavior of this operation is undefined if 
  220.      * the specified collection is modified while the operation is in 
  221.      * progress.  (Note that this will occur if the specified collection is 
  222.      * this list, and it's nonempty.) 
  223.      * 
  224.      * @param c collection containing elements to be added to this list 
  225.      * @return <tt>true</tt> if this list changed as a result of the call 
  226.      * @throws NullPointerException if the specified collection is null 
  227.      */  
  228.     public boolean addAll(Collection<? extends E> c) {  
  229.         return addAll(size, c);  
  230.     }  
  231.     /** 
  232.      * Inserts all of the elements in the specified collection into this 
  233.      * list, starting at the specified position.  Shifts the element 
  234.      * currently at that position (if any) and any subsequent elements to 
  235.      * the right (increases their indices).  The new elements will appear 
  236.      * in the list in the order that they are returned by the 
  237.      * specified collection's iterator. 
  238.      * 
  239.      * @param index index at which to insert the first element 
  240.      *              from the specified collection 
  241.      * @param c collection containing elements to be added to this list 
  242.      * @return <tt>true</tt> if this list changed as a result of the call 
  243.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  244.      * @throws NullPointerException if the specified collection is null 
  245.      */  
  246.     public boolean addAll(int index, Collection<? extends E> c) {  
  247.         if (index < 0 || index > size)  
  248.             throw new IndexOutOfBoundsException("Index: "+index+  
  249.                                                 ", Size: "+size);  
  250.         Object[] a = c.toArray();  
  251.         int numNew = a.length;  
  252.         if (numNew==0)  
  253.             return false;  
  254.     modCount++;  
  255.         Entry<E> successor = (index==size ? header : entry(index));  
  256.         Entry<E> predecessor = successor.previous;  
  257.     for (int i=0; i<numNew; i++) {  
  258.             Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);  
  259.             predecessor.next = e;  
  260.             predecessor = e;  
  261.         }  
  262.         successor.previous = predecessor;  
  263.         size += numNew;  
  264.         return true;  
  265.     }  
  266.     /** 
  267.      * Removes all of the elements from this list. 
  268.      */  
  269.     public void clear() {  
  270.         Entry<E> e = header.next;  
  271.         while (e != header) {  
  272.             Entry<E> next = e.next;  
  273.             e.next = e.previous = null;  
  274.             e.element = null;  
  275.             e = next;  
  276.         }  
  277.         header.next = header.previous = header;  
  278.         size = 0;  
  279.     modCount++;  
  280.     }  
  281.   
  282.     // Positional Access Operations  
  283.     /** 
  284.      * Returns the element at the specified position in this list. 
  285.      * 
  286.      * @param index index of the element to return 
  287.      * @return the element at the specified position in this list 
  288.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  289.      */  
  290.     public E get(int index) {  
  291.         return entry(index).element;  
  292.     }  
  293.     /** 
  294.      * Replaces the element at the specified position in this list with the 
  295.      * specified element. 
  296.      * 
  297.      * @param index index of the element to replace 
  298.      * @param element element to be stored at the specified position 
  299.      * @return the element previously at the specified position 
  300.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  301.      */  
  302.     public E set(int index, E element) {  
  303.         Entry<E> e = entry(index);  
  304.         E oldVal = e.element;  
  305.         e.element = element;  
  306.         return oldVal;  
  307.     }  
  308.     /** 
  309.      * Inserts the specified element at the specified position in this list. 
  310.      * Shifts the element currently at that position (if any) and any 
  311.      * subsequent elements to the right (adds one to their indices). 
  312.      * 
  313.      * @param index index at which the specified element is to be inserted 
  314.      * @param element element to be inserted 
  315.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  316.      */  
  317.     public void add(int index, E element) {  
  318.         addBefore(element, (index==size ? header : entry(index)));  
  319.     }  
  320.     /** 
  321.      * Removes the element at the specified position in this list.  Shifts any 
  322.      * subsequent elements to the left (subtracts one from their indices). 
  323.      * Returns the element that was removed from the list. 
  324.      * 
  325.      * @param index the index of the element to be removed 
  326.      * @return the element previously at the specified position 
  327.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  328.      */  
  329.     public E remove(int index) {  
  330.         return remove(entry(index));  
  331.     }  
  332.     /** 
  333.      * Returns the indexed entry. 
  334.      */  
  335.     private Entry<E> entry(int index) {  
  336.         if (index < 0 || index >= size)  
  337.             throw new IndexOutOfBoundsException("Index: "+index+  
  338.                                                 ", Size: "+size);  
  339.         Entry<E> e = header;  
  340.         if (index < (size >> 1)) {  
  341.             for (int i = 0; i <= index; i++)  
  342.                 e = e.next;  
  343.         } else {  
  344.             for (int i = size; i > index; i--)  
  345.                 e = e.previous;  
  346.         }  
  347.         return e;  
  348.     }  
  349.   
  350.     // Search Operations  
  351.     /** 
  352.      * Returns the index of the first occurrence of the specified element 
  353.      * in this list, or -1 if this list does not contain the element. 
  354.      * More formally, returns the lowest index <tt>i</tt> such that 
  355.      * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, 
  356.      * or -1 if there is no such index. 
  357.      * 
  358.      * @param o element to search for 
  359.      * @return the index of the first occurrence of the specified element in 
  360.      *         this list, or -1 if this list does not contain the element 
  361.      */  
  362.     public int indexOf(Object o) {  
  363.         int index = 0;  
  364.         if (o==null) {  
  365.             for (Entry e = header.next; e != header; e = e.next) {  
  366.                 if (e.element==null)  
  367.                     return index;  
  368.                 index++;  
  369.             }  
  370.         } else {  
  371.             for (Entry e = header.next; e != header; e = e.next) {  
  372.                 if (o.equals(e.element))  
  373.                     return index;  
  374.                 index++;  
  375.             }  
  376.         }  
  377.         return -1;  
  378.     }  
  379.     /** 
  380.      * Returns the index of the last occurrence of the specified element 
  381.      * in this list, or -1 if this list does not contain the element. 
  382.      * More formally, returns the highest index <tt>i</tt> such that 
  383.      * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, 
  384.      * or -1 if there is no such index. 
  385.      * 
  386.      * @param o element to search for 
  387.      * @return the index of the last occurrence of the specified element in 
  388.      *         this list, or -1 if this list does not contain the element 
  389.      */  
  390.     public int lastIndexOf(Object o) {  
  391.         int index = size;  
  392.         if (o==null) {  
  393.             for (Entry e = header.previous; e != header; e = e.previous) {  
  394.                 index--;  
  395.                 if (e.element==null)  
  396.                     return index;  
  397.             }  
  398.         } else {  
  399.             for (Entry e = header.previous; e != header; e = e.previous) {  
  400.                 index--;  
  401.                 if (o.equals(e.element))  
  402.                     return index;  
  403.             }  
  404.         }  
  405.         return -1;  
  406.     }  
  407.     // Queue operations.  
  408.     /** 
  409.      * Retrieves, but does not remove, the head (first element) of this list. 
  410.      * @return the head of this list, or <tt>null</tt> if this list is empty 
  411.      * @since 1.5 
  412.      */  
  413.     public E peek() {  
  414.         if (size==0)  
  415.             return null;  
  416.         return getFirst();  
  417.     }  
  418.     /** 
  419.      * Retrieves, but does not remove, the head (first element) of this list. 
  420.      * @return the head of this list 
  421.      * @throws NoSuchElementException if this list is empty 
  422.      * @since 1.5 
  423.      */  
  424.     public E element() {  
  425.         return getFirst();  
  426.     }  
  427.     /** 
  428.      * Retrieves and removes the head (first element) of this list 
  429.      * @return the head of this list, or <tt>null</tt> if this list is empty 
  430.      * @since 1.5 
  431.      */  
  432.     public E poll() {  
  433.         if (size==0)  
  434.             return null;  
  435.         return removeFirst();  
  436.     }  
  437.     /** 
  438.      * Retrieves and removes the head (first element) of this list. 
  439.      * 
  440.      * @return the head of this list 
  441.      * @throws NoSuchElementException if this list is empty 
  442.      * @since 1.5 
  443.      */  
  444.     public E remove() {  
  445.         return removeFirst();  
  446.     }  
  447.     /** 
  448.      * Adds the specified element as the tail (last element) of this list. 
  449.      * 
  450.      * @param e the element to add 
  451.      * @return <tt>true</tt> (as specified by {@link Queue#offer}) 
  452.      * @since 1.5 
  453.      */  
  454.     public boolean offer(E e) {  
  455.         return add(e);  
  456.     }  
  457.     // Deque operations  
  458.     /** 
  459.      * Inserts the specified element at the front of this list. 
  460.      * 
  461.      * @param e the element to insert 
  462.      * @return <tt>true</tt> (as specified by {@link Deque#offerFirst}) 
  463.      * @since 1.6 
  464.      */  
  465.     public boolean offerFirst(E e) {  
  466.         addFirst(e);  
  467.         return true;  
  468.     }  
  469.     /** 
  470.      * Inserts the specified element at the end of this list. 
  471.      * 
  472.      * @param e the element to insert 
  473.      * @return <tt>true</tt> (as specified by {@link Deque#offerLast}) 
  474.      * @since 1.6 
  475.      */  
  476.     public boolean offerLast(E e) {  
  477.         addLast(e);  
  478.         return true;  
  479.     }  
  480.     /** 
  481.      * Retrieves, but does not remove, the first element of this list, 
  482.      * or returns <tt>null</tt> if this list is empty. 
  483.      * 
  484.      * @return the first element of this list, or <tt>null</tt> 
  485.      *         if this list is empty 
  486.      * @since 1.6 
  487.      */  
  488.     public E peekFirst() {  
  489.         if (size==0)  
  490.             return null;  
  491.         return getFirst();  
  492.     }  
  493.     /** 
  494.      * Retrieves, but does not remove, the last element of this list, 
  495.      * or returns <tt>null</tt> if this list is empty. 
  496.      * 
  497.      * @return the last element of this list, or <tt>null</tt> 
  498.      *         if this list is empty 
  499.      * @since 1.6 
  500.      */  
  501.     public E peekLast() {  
  502.         if (size==0)  
  503.             return null;  
  504.         return getLast();  
  505.     }  
  506.     /** 
  507.      * Retrieves and removes the first element of this list, 
  508.      * or returns <tt>null</tt> if this list is empty. 
  509.      * 
  510.      * @return the first element of this list, or <tt>null</tt> if 
  511.      *     this list is empty 
  512.      * @since 1.6 
  513.      */  
  514.     public E pollFirst() {  
  515.         if (size==0)  
  516.             return null;  
  517.         return removeFirst();  
  518.     }  
  519.     /** 
  520.      * Retrieves and removes the last element of this list, 
  521.      * or returns <tt>null</tt> if this list is empty. 
  522.      * 
  523.      * @return the last element of this list, or <tt>null</tt> if 
  524.      *     this list is empty 
  525.      * @since 1.6 
  526.      */  
  527.     public E pollLast() {  
  528.         if (size==0)  
  529.             return null;  
  530.         return removeLast();  
  531.     }  
  532.     /** 
  533.      * Pushes an element onto the stack represented by this list.  In other 
  534.      * words, inserts the element at the front of this list. 
  535.      * 
  536.      * <p>This method is equivalent to {@link #addFirst}. 
  537.      * 
  538.      * @param e the element to push 
  539.      * @since 1.6 
  540.      */  
  541.     public void push(E e) {  
  542.         addFirst(e);  
  543.     }  
  544.     /** 
  545.      * Pops an element from the stack represented by this list.  In other 
  546.      * words, removes and returns the first element of this list. 
  547.      * 
  548.      * <p>This method is equivalent to {@link #removeFirst()}. 
  549.      * 
  550.      * @return the element at the front of this list (which is the top 
  551.      *         of the stack represented by this list) 
  552.      * @throws NoSuchElementException if this list is empty 
  553.      * @since 1.6 
  554.      */  
  555.     public E pop() {  
  556.         return removeFirst();  
  557.     }  
  558.     /** 
  559.      * Removes the first occurrence of the specified element in this 
  560.      * list (when traversing the list from head to tail).  If the list 
  561.      * does not contain the element, it is unchanged. 
  562.      * 
  563.      * @param o element to be removed from this list, if present 
  564.      * @return <tt>true</tt> if the list contained the specified element 
  565.      * @since 1.6 
  566.      */  
  567.     public boolean removeFirstOccurrence(Object o) {  
  568.         return remove(o);  
  569.     }  
  570.     /** 
  571.      * Removes the last occurrence of the specified element in this 
  572.      * list (when traversing the list from head to tail).  If the list 
  573.      * does not contain the element, it is unchanged. 
  574.      * 
  575.      * @param o element to be removed from this list, if present 
  576.      * @return <tt>true</tt> if the list contained the specified element 
  577.      * @since 1.6 
  578.      */  
  579.     public boolean removeLastOccurrence(Object o) {  
  580.         if (o==null) {  
  581.             for (Entry<E> e = header.previous; e != header; e = e.previous) {  
  582.                 if (e.element==null) {  
  583.                     remove(e);  
  584.                     return true;  
  585.                 }  
  586.             }  
  587.         } else {  
  588.             for (Entry<E> e = header.previous; e != header; e = e.previous) {  
  589.                 if (o.equals(e.element)) {  
  590.                     remove(e);  
  591.                     return true;  
  592.                 }  
  593.             }  
  594.         }  
  595.         return false;  
  596.     }  
  597.     /** 
  598.      * Returns a list-iterator of the elements in this list (in proper 
  599.      * sequence), starting at the specified position in the list. 
  600.      * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p> 
  601.      * 
  602.      * The list-iterator is <i>fail-fast</i>: if the list is structurally 
  603.      * modified at any time after the Iterator is created, in any way except 
  604.      * through the list-iterator's own <tt>remove</tt> or <tt>add</tt> 
  605.      * methods, the list-iterator will throw a 
  606.      * <tt>ConcurrentModificationException</tt>.  Thus, in the face of 
  607.      * concurrent modification, the iterator fails quickly and cleanly, rather 
  608.      * than risking arbitrary, non-deterministic behavior at an undetermined 
  609.      * time in the future. 
  610.      * 
  611.      * @param index index of the first element to be returned from the 
  612.      *              list-iterator (by a call to <tt>next</tt>) 
  613.      * @return a ListIterator of the elements in this list (in proper 
  614.      *         sequence), starting at the specified position in the list 
  615.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  616.      * @see List#listIterator(int) 
  617.      */  
  618.     public ListIterator<E> listIterator(int index) {  
  619.     return new ListItr(index);  
  620.     }  
  621.     private class ListItr implements ListIterator<E> {  
  622.     private Entry<E> lastReturned = header;  
  623.     private Entry<E> next;  
  624.     private int nextIndex;  
  625.     private int expectedModCount = modCount;  
  626.     ListItr(int index) {  
  627.         if (index < 0 || index > size)  
  628.         throw new IndexOutOfBoundsException("Index: "+index+  
  629.                             ", Size: "+size);  
  630.         if (index < (size >> 1)) {  
  631.         next = header.next;  
  632.         for (nextIndex=0; nextIndex<index; nextIndex++)  
  633.             next = next.next;  
  634.         } else {  
  635.         next = header;  
  636.         for (nextIndex=size; nextIndex>index; nextIndex--)  
  637.             next = next.previous;  
  638.         }  
  639.     }  
  640.     public boolean hasNext() {  
  641.         return nextIndex != size;  
  642.     }  
  643.     public E next() {  
  644.         checkForComodification();  
  645.         if (nextIndex == size)  
  646.         throw new NoSuchElementException();  
  647.         lastReturned = next;  
  648.         next = next.next;  
  649.         nextIndex++;  
  650.         return lastReturned.element;  
  651.     }  
  652.     public boolean hasPrevious() {  
  653.         return nextIndex != 0;  
  654.     }  
  655.     public E previous() {  
  656.         if (nextIndex == 0)  
  657.         throw new NoSuchElementException();  
  658.         lastReturned = next = next.previous;  
  659.         nextIndex--;  
  660.         checkForComodification();  
  661.         return lastReturned.element;  
  662.     }  
  663.     public int nextIndex() {  
  664.         return nextIndex;  
  665.     }  
  666.     public int previousIndex() {  
  667.         return nextIndex-1;  
  668.     }  
  669.     public void remove() {  
  670.             checkForComodification();  
  671.             Entry<E> lastNext = lastReturned.next;  
  672.             try {  
  673.                 LinkedList.this.remove(lastReturned);  
  674.             } catch (NoSuchElementException e) {  
  675.                 throw new IllegalStateException();  
  676.             }  
  677.         if (next==lastReturned)  
  678.                 next = lastNext;  
  679.             else  
  680.         nextIndex--;  
  681.         lastReturned = header;  
  682.         expectedModCount++;  
  683.     }  
  684.     public void set(E e) {  
  685.         if (lastReturned == header)  
  686.         throw new IllegalStateException();  
  687.         checkForComodification();  
  688.         lastReturned.element = e;  
  689.     }  
  690.     public void add(E e) {  
  691.         checkForComodification();  
  692.         lastReturned = header;  
  693.         addBefore(e, next);  
  694.         nextIndex++;  
  695.         expectedModCount++;  
  696.     }  
  697.     final void checkForComodification() {  
  698.         if (modCount != expectedModCount)  
  699.         throw new ConcurrentModificationException();  
  700.     }  
  701.     }  
  702.     private static class Entry<E> {  
  703.     E element;  
  704.     Entry<E> next;  
  705.     Entry<E> previous;  
  706.     Entry(E element, Entry<E> next, Entry<E> previous) {  
  707.         this.element = element;  
  708.         this.next = next;  
  709.         this.previous = previous;  
  710.     }  
  711.     }  
  712.     private Entry<E> addBefore(E e, Entry<E> entry) {  
  713.     Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);  
  714.     newEntry.previous.next = newEntry;  
  715.     newEntry.next.previous = newEntry;  
  716.     size++;  
  717.     modCount++;  
  718.     return newEntry;  
  719.     }  
  720.     private E remove(Entry<E> e) {  
  721.     if (e == header)  
  722.         throw new NoSuchElementException();  
  723.         E result = e.element;  
  724.     e.previous.next = e.next;  
  725.     e.next.previous = e.previous;  
  726.         e.next = e.previous = null;  
  727.         e.element = null;  
  728.     size--;  
  729.     modCount++;  
  730.         return result;  
  731.     }  
  732.     /** 
  733.      * @since 1.6 
  734.      */  
  735.     public Iterator<E> descendingIterator() {  
  736.         return new DescendingIterator();  
  737.     }  
  738.     /** Adapter to provide descending iterators via ListItr.previous */  
  739.     private class DescendingIterator implements Iterator {  
  740.         final ListItr itr = new ListItr(size());  
  741.     public boolean hasNext() {  
  742.         return itr.hasPrevious();  
  743.     }  
  744.     public E next() {  
  745.             return itr.previous();  
  746.         }  
  747.     public void remove() {  
  748.             itr.remove();  
  749.         }  
  750.     }  
  751.     /** 
  752.      * Returns a shallow copy of this <tt>LinkedList</tt>. (The elements 
  753.      * themselves are not cloned.) 
  754.      * 
  755.      * @return a shallow copy of this <tt>LinkedList</tt> instance 
  756.      */  
  757.     public Object clone() {  
  758.         LinkedList<E> clone = null;  
  759.     try {  
  760.         clone = (LinkedList<E>) super.clone();  
  761.     } catch (CloneNotSupportedException e) {  
  762.         throw new InternalError();  
  763.     }  
  764.         // Put clone into "virgin" state  
  765.         clone.header = new Entry<E>(nullnullnull);  
  766.         clone.header.next = clone.header.previous = clone.header;  
  767.         clone.size = 0;  
  768.         clone.modCount = 0;  
  769.         // Initialize clone with our elements  
  770.         for (Entry<E> e = header.next; e != header; e = e.next)  
  771.             clone.add(e.element);  
  772.         return clone;  
  773.     }  
  774.     /** 
  775.      * Returns an array containing all of the elements in this list 
  776.      * in proper sequence (from first to last element). 
  777.      * 
  778.      * <p>The returned array will be "safe" in that no references to it are 
  779.      * maintained by this list.  (In other words, this method must allocate 
  780.      * a new array).  The caller is thus free to modify the returned array. 
  781.      * 
  782.      * <p>This method acts as bridge between array-based and collection-based 
  783.      * APIs. 
  784.      * 
  785.      * @return an array containing all of the elements in this list 
  786.      *         in proper sequence 
  787.      */  
  788.     public Object[] toArray() {  
  789.     Object[] result = new Object[size];  
  790.         int i = 0;  
  791.         for (Entry<E> e = header.next; e != header; e = e.next)  
  792.             result[i++] = e.element;  
  793.     return result;  
  794.     }  
  795.     /** 
  796.      * Returns an array containing all of the elements in this list in 
  797.      * proper sequence (from first to last element); the runtime type of 
  798.      * the returned array is that of the specified array.  If the list fits 
  799.      * in the specified array, it is returned therein.  Otherwise, a new 
  800.      * array is allocated with the runtime type of the specified array and 
  801.      * the size of this list. 
  802.      * 
  803.      * <p>If the list fits in the specified array with room to spare (i.e., 
  804.      * the array has more elements than the list), the element in the array 
  805.      * immediately following the end of the list is set to <tt>null</tt>. 
  806.      * (This is useful in determining the length of the list <i>only</i> if 
  807.      * the caller knows that the list does not contain any null elements.) 
  808.      * 
  809.      * <p>Like the {@link #toArray()} method, this method acts as bridge between 
  810.      * array-based and collection-based APIs.  Further, this method allows 
  811.      * precise control over the runtime type of the output array, and may, 
  812.      * under certain circumstances, be used to save allocation costs. 
  813.      * 
  814.      * <p>Suppose <tt>x</tt> is a list known to contain only strings. 
  815.      * The following code can be used to dump the list into a newly 
  816.      * allocated array of <tt>String</tt>: 
  817.      * 
  818.      * <pre> 
  819.      *     String[] y = x.toArray(new String[0]);</pre> 
  820.      * 
  821.      * Note that <tt>toArray(new Object[0])</tt> is identical in function to 
  822.      * <tt>toArray()</tt>. 
  823.      * 
  824.      * @param a the array into which the elements of the list are to 
  825.      *          be stored, if it is big enough; otherwise, a new array of the 
  826.      *          same runtime type is allocated for this purpose. 
  827.      * @return an array containing the elements of the list 
  828.      * @throws ArrayStoreException if the runtime type of the specified array 
  829.      *         is not a supertype of the runtime type of every element in 
  830.      *         this list 
  831.      * @throws NullPointerException if the specified array is null 
  832.      */  
  833.     public <T> T[] toArray(T[] a) {  
  834.         if (a.length < size)  
  835.             a = (T[])java.lang.reflect.Array.newInstance(  
  836.                                 a.getClass().getComponentType(), size);  
  837.         int i = 0;  
  838.     Object[] result = a;  
  839.         for (Entry<E> e = header.next; e != header; e = e.next)  
  840.             result[i++] = e.element;  
  841.         if (a.length > size)  
  842.             a[size] = null;  
  843.         return a;  
  844.     }  
  845.     private static final long serialVersionUID = 876323262645176354L;  
  846.     /** 
  847.      * Save the state of this <tt>LinkedList</tt> instance to a stream (that 
  848.      * is, serialize it). 
  849.      * 
  850.      * @serialData The size of the list (the number of elements it 
  851.      *             contains) is emitted (int), followed by all of its 
  852.      *             elements (each an Object) in the proper order. 
  853.      */  
  854.     private void writeObject(java.io.ObjectOutputStream s)  
  855.         throws java.io.IOException {  
  856.     // Write out any hidden serialization magic  
  857.     s.defaultWriteObject();  
  858.         // Write out size  
  859.         s.writeInt(size);  
  860.     // Write out all elements in the proper order.  
  861.         for (Entry e = header.next; e != header; e = e.next)  
  862.             s.writeObject(e.element);  
  863.     }  
  864.     /** 
  865.      * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is 
  866.      * deserialize it). 
  867.      */  
  868.     private void readObject(java.io.ObjectInputStream s)  
  869.         throws java.io.IOException, ClassNotFoundException {  
  870.     // Read in any hidden serialization magic  
  871.     s.defaultReadObject();  
  872.         // Read in size  
  873.         int size = s.readInt();  
  874.         // Initialize header  
  875.         header = new Entry<E>(nullnullnull);  
  876.         header.next = header.previous = header;  
  877.     // Read in all elements in the proper order.  
  878.     for (int i=0; i<size; i++)  
  879.             addBefore((E)s.readObject(), header);  
  880.     }  
  881. }  
原文地址:https://www.cnblogs.com/Free-Thinker/p/3581463.html