--- jsr166/src/main/java/util/LinkedList.java 2005/05/17 06:36:47 1.30 +++ jsr166/src/main/java/util/LinkedList.java 2010/12/02 04:17:19 1.53 @@ -1,48 +1,59 @@ /* - * %W% %E% + * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * - * Copyright 2005 Sun Microsystems, Inc. All rights reserved. - * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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; /** - * Linked list implementation of the List interface. Implements all - * optional list operations, and permits all elements (including - * null). In addition to implementing the List interface, - * the LinkedList class provides uniformly named methods to - * get, remove and insert an element at the - * beginning and end of the list. These operations allow linked lists to be - * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque - * double-ended queue}.

- * - * The class implements the Deque interface, providing - * first-in-first-out queue operations for add, - * poll, along with other stack and deque operations.

+ * Doubly-linked list implementation of the {@code List} and {@code Deque} + * interfaces. Implements all optional list operations, and permits all + * elements (including {@code null}). * - * All of the operations perform as could be expected for a doubly-linked + *

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.

+ * the beginning or the end, whichever is closer to the specified index. + * + *

Note that this implementation is not synchronized. + * If multiple threads access a linked list concurrently, and at least + * one of the threads modifies the list structurally, it must 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. * - * Note that this implementation is not synchronized. If multiple - * threads access a list concurrently, and at least one of the threads - * modifies the list structurally, it must 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 - * Collections.synchronizedList method. This is best done at creation time, - * to prevent accidental unsynchronized access to the list:

- *     List list = Collections.synchronizedList(new LinkedList(...));
- * 
+ * 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:
+ *   List list = Collections.synchronizedList(new LinkedList(...));
* - *

The iterators returned by this class's iterator and - * listIterator methods are fail-fast: if the list is + *

The iterators returned by this class's {@code iterator} and + * {@code listIterator} methods are fail-fast: if the list is * structurally modified at any time after the iterator is created, in - * any way except through the Iterator's own remove or - * add methods, the iterator will throw a {@link + * 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 @@ -51,21 +62,18 @@ package java.util; *

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 ConcurrentModificationException on a best-effort basis. + * 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: the fail-fast behavior of iterators * should be used only to detect bugs. * *

This class is a member of the - * + * * Java Collections Framework. * * @author Josh Bloch - * @version %I%, %G% - * @see List - * @see ArrayList - * @see Vector - * @see Collections#synchronizedList(List) + * @see List + * @see ArrayList * @since 1.2 * @param the type of elements held in this collection */ @@ -74,14 +82,26 @@ public class LinkedList extends AbstractSequentialList implements List, Deque, Cloneable, java.io.Serializable { - private transient Entry header = new Entry(null, null, null); - private transient int size = 0; + transient int size = 0; + + /** + * Pointer to first node. + * Invariant: (first == null && last == null) || + * (first.prev == null && first.item != null) + */ + transient Node first; + + /** + * Pointer to last node. + * Invariant: (first == null && last == null) || + * (last.next == null && last.item != null) + */ + transient Node last; /** * Constructs an empty list. */ public LinkedList() { - header.next = header.previous = header; } /** @@ -92,10 +112,123 @@ public class LinkedList * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ - public LinkedList(Collection c) { - this(); - addAll(c); - } + public LinkedList(Collection c) { + this(); + addAll(c); + } + + /** + * Links e as first element. + */ + private void linkFirst(E e) { + final Node f = first; + final Node 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 l = last; + final Node 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 succ) { + // assert succ != null; + final Node pred = succ.prev; + final Node 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 f) { + // assert f == first && f != null; + final E element = f.item; + final Node 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 l) { + // assert l == last && l != null; + final E element = l.item; + final Node 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 x) { + // assert x != null; + final E element = x.item; + final Node next = x.next; + final Node 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. @@ -104,10 +237,10 @@ public class LinkedList * @throws NoSuchElementException if this list is empty */ public E getFirst() { - if (size==0) - throw new NoSuchElementException(); - - return header.next.element; + final Node f = first; + if (f == null) + throw new NoSuchElementException(); + return f.item; } /** @@ -116,11 +249,11 @@ public class LinkedList * @return the last element in this list * @throws NoSuchElementException if this list is empty */ - public E getLast() { - if (size==0) - throw new NoSuchElementException(); - - return header.previous.element; + public E getLast() { + final Node l = last; + if (l == null) + throw new NoSuchElementException(); + return l.item; } /** @@ -130,7 +263,10 @@ public class LinkedList * @throws NoSuchElementException if this list is empty */ public E removeFirst() { - return remove(header.next); + final Node f = first; + if (f == null) + throw new NoSuchElementException(); + return unlinkFirst(f); } /** @@ -140,36 +276,40 @@ public class LinkedList * @throws NoSuchElementException if this list is empty */ public E removeLast() { - return remove(header.previous); + final Node l = last; + if (l == null) + throw new NoSuchElementException(); + return unlinkLast(l); } /** - * Inserts the given element at the beginning of this list. + * Inserts the specified element at the beginning of this list. * - * @param e the element to be inserted at the beginning of this list + * @param e the element to add */ public void addFirst(E e) { - addBefore(e, header.next); + linkFirst(e); } /** - * Appends the given element to the end of this list. (Identical in - * function to the add method; included only for consistency.) + * Appends the specified element to the end of this list. + * + *

This method is equivalent to {@link #add}. * - * @param e the element to be inserted at the end of this list + * @param e the element to add */ public void addLast(E e) { - addBefore(e, header); + linkLast(e); } /** - * Returns true if this list contains the specified element. - * More formally, returns true if and only if this list contains - * at least one element e such that + * 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 * (o==null ? e==null : o.equals(e)). * * @param o element whose presence in this list is to be tested - * @return true if this list contains the specified element + * @return {@code true} if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) != -1; @@ -181,17 +321,19 @@ public class LinkedList * @return the number of elements in this list */ public int size() { - return size; + return size; } /** * Appends the specified element to the end of this list. * + *

This method is equivalent to {@link #addLast}. + * * @param e element to be appended to this list - * @return true (as per the spec for {@link Collection#add}) + * @return {@code true} (as specified by {@link Collection#add}) */ public boolean add(E e) { - addBefore(e, header); + linkLast(e); return true; } @@ -199,27 +341,27 @@ public class LinkedList * 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 - * i such that + * {@code i} such that * (o==null ? get(i)==null : o.equals(get(i))) - * (if such an element exists). Returns true if this list + * (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 true if this list contained the specified element + * @return {@code true} if this list contained the specified element */ public boolean remove(Object o) { - if (o==null) { - for (Entry e = header.next; e != header; e = e.next) { - if (e.element==null) { - remove(e); + if (o == null) { + for (Node x = first; x != null; x = x.next) { + if (x.item == null) { + unlink(x); return true; } } } else { - for (Entry e = header.next; e != header; e = e.next) { - if (o.equals(e.element)) { - remove(e); + for (Node x = first; x != null; x = x.next) { + if (o.equals(x.item)) { + unlink(x); return true; } } @@ -232,11 +374,11 @@ public class LinkedList * 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. (This implies that the behavior of this call is undefined if - * the specified Collection is this list, and this list is nonempty.) + * progress. (Note that this will occur if the specified collection is + * this list, and it's nonempty.) * - * @param c the elements to be inserted into this list - * @return true if this list changed as a result of the call + * @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 c) { @@ -253,48 +395,69 @@ public class LinkedList * * @param index index at which to insert the first element * from the specified collection - * @param c elements to be inserted into this list - * @return true if this list changed as a result of the call + * @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 c) { - if (index < 0 || index > size) - throw new IndexOutOfBoundsException("Index: "+index+ - ", Size: "+size); + checkPositionIndex(index); + Object[] a = c.toArray(); int numNew = a.length; - if (numNew==0) + if (numNew == 0) return false; - modCount++; - Entry successor = (index==size ? header : entry(index)); - Entry predecessor = successor.previous; - for (int i=0; i e = new Entry((E)a[i], successor, predecessor); - predecessor.next = e; - predecessor = e; + Node 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 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; } - successor.previous = predecessor; 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() { - Entry e = header.next; - while (e != header) { - Entry next = e.next; - e.next = e.previous = null; - e.element = null; - e = next; + // 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 x = first; x != null; ) { + Node next = x.next; + x.item = null; + x.next = null; + x.prev = null; + x = next; } - header.next = header.previous = header; + first = last = null; size = 0; - modCount++; + modCount++; } @@ -308,7 +471,8 @@ public class LinkedList * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { - return entry(index).element; + checkElementIndex(index); + return node(index).item; } /** @@ -321,9 +485,10 @@ public class LinkedList * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { - Entry e = entry(index); - E oldVal = e.element; - e.element = element; + checkElementIndex(index); + Node x = node(index); + E oldVal = x.item; + x.item = element; return oldVal; } @@ -337,7 +502,12 @@ public class LinkedList * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { - addBefore(element, (index==size ? header : entry(index))); + checkPositionIndex(index); + + if (index == size) + linkLast(element); + else + linkBefore(element, node(index)); } /** @@ -350,34 +520,69 @@ public class LinkedList * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { - return remove(entry(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; } /** - * Returns the indexed entry. + * 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 Entry entry(int index) { - if (index < 0 || index >= size) - throw new IndexOutOfBoundsException("Index: "+index+ - ", Size: "+size); - Entry e = header; + 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 node(int index) { + // assert isElementIndex(index); + if (index < (size >> 1)) { - for (int i = 0; i <= index; i++) - e = e.next; + Node x = first; + for (int i = 0; i < index; i++) + x = x.next; + return x; } else { - for (int i = size; i > index; i--) - e = e.previous; + Node x = last; + for (int i = size - 1; i > index; i--) + x = x.prev; + return x; } - return e; } - // 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 i such that + * More formally, returns the lowest index {@code i} such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * @@ -387,15 +592,15 @@ public class LinkedList */ public int indexOf(Object o) { int index = 0; - if (o==null) { - for (Entry e = header.next; e != header; e = e.next) { - if (e.element==null) + if (o == null) { + for (Node x = first; x != null; x = x.next) { + if (x.item == null) return index; index++; } } else { - for (Entry e = header.next; e != header; e = e.next) { - if (o.equals(e.element)) + for (Node x = first; x != null; x = x.next) { + if (o.equals(x.item)) return index; index++; } @@ -406,7 +611,7 @@ public class LinkedList /** * 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 i such that + * More formally, returns the highest index {@code i} such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * @@ -416,16 +621,16 @@ public class LinkedList */ public int lastIndexOf(Object o) { int index = size; - if (o==null) { - for (Entry e = header.previous; e != header; e = e.previous) { + if (o == null) { + for (Node x = last; x != null; x = x.prev) { index--; - if (e.element==null) + if (x.item == null) return index; } } else { - for (Entry e = header.previous; e != header; e = e.previous) { + for (Node x = last; x != null; x = x.prev) { index--; - if (o.equals(e.element)) + if (o.equals(x.item)) return index; } } @@ -436,17 +641,18 @@ public class LinkedList /** * Retrieves, but does not remove, the head (first element) of this list. - * @return the head of this list, or null if this list is empty + * + * @return the head of this list, or {@code null} if this list is empty * @since 1.5 */ public E peek() { - if (size==0) - return null; - return getFirst(); + final Node 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 @@ -456,14 +662,14 @@ public class LinkedList } /** - * Retrieves and removes the head (first element) of this list - * @return the head of this list, or null if this list is empty + * 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() { - if (size==0) - return null; - return removeFirst(); + final Node f = first; + return (f == null) ? null : unlinkFirst(f); } /** @@ -481,7 +687,7 @@ public class LinkedList * Adds the specified element as the tail (last element) of this list. * * @param e the element to add - * @return true (as per the spec for {@link Queue#offer}) + * @return {@code true} (as specified by {@link Queue#offer}) * @since 1.5 */ public boolean offer(E e) { @@ -493,7 +699,7 @@ public class LinkedList * Inserts the specified element at the front of this list. * * @param e the element to insert - * @return true (as per the spec for {@link Deque#offerFirst}) + * @return {@code true} (as specified by {@link Deque#offerFirst}) * @since 1.6 */ public boolean offerFirst(E e) { @@ -505,7 +711,7 @@ public class LinkedList * Inserts the specified element at the end of this list. * * @param e the element to insert - * @return true (as per the spec for {@link Deque#offerLast}) + * @return {@code true} (as specified by {@link Deque#offerLast}) * @since 1.6 */ public boolean offerLast(E e) { @@ -515,58 +721,54 @@ public class LinkedList /** * Retrieves, but does not remove, the first element of this list, - * or returns null if this list is empty. + * or returns {@code null} if this list is empty. * - * @return the first element of this list, or null + * @return the first element of this list, or {@code null} * if this list is empty * @since 1.6 */ public E peekFirst() { - if (size==0) - return null; - return getFirst(); - } + final Node f = first; + return (f == null) ? null : f.item; + } /** * Retrieves, but does not remove, the last element of this list, - * or returns null if this list is empty. + * or returns {@code null} if this list is empty. * - * @return the last element of this list, or null + * @return the last element of this list, or {@code null} * if this list is empty * @since 1.6 */ public E peekLast() { - if (size==0) - return null; - return getLast(); + final Node l = last; + return (l == null) ? null : l.item; } /** - * Retrieves and removes the first element of this list, or - * null if this list is empty. + * 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 null if + * @return the first element of this list, or {@code null} if * this list is empty * @since 1.6 */ public E pollFirst() { - if (size==0) - return null; - return removeFirst(); + final Node f = first; + return (f == null) ? null : unlinkFirst(f); } /** - * Retrieves and removes the last element of this list, or - * null if this list is empty. + * 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 null if + * @return the last element of this list, or {@code null} if * this list is empty * @since 1.6 */ public E pollLast() { - if (size==0) - return null; - return removeLast(); + final Node l = last; + return (l == null) ? null : unlinkLast(l); } /** @@ -603,7 +805,7 @@ public class LinkedList * does not contain the element, it is unchanged. * * @param o element to be removed from this list, if present - * @return true if the list contained the specified element + * @return {@code true} if the list contained the specified element * @since 1.6 */ public boolean removeFirstOccurrence(Object o) { @@ -616,21 +818,21 @@ public class LinkedList * does not contain the element, it is unchanged. * * @param o element to be removed from this list, if present - * @return true if the list contained the specified element + * @return {@code true} if the list contained the specified element * @since 1.6 */ public boolean removeLastOccurrence(Object o) { - if (o==null) { - for (Entry e = header.previous; e != header; e = e.previous) { - if (e.element==null) { - remove(e); + if (o == null) { + for (Node x = last; x != null; x = x.prev) { + if (x.item == null) { + unlink(x); return true; } } } else { - for (Entry e = header.previous; e != header; e = e.previous) { - if (o.equals(e.element)) { - remove(e); + for (Node x = last; x != null; x = x.prev) { + if (o.equals(x.item)) { + unlink(x); return true; } } @@ -641,181 +843,178 @@ public class LinkedList /** * 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 List.listIterator(int).

+ * Obeys the general contract of {@code List.listIterator(int)}.

* * The list-iterator is fail-fast: if the list is structurally * modified at any time after the Iterator is created, in any way except - * through the list-iterator's own remove or add + * through the list-iterator's own {@code remove} or {@code add} * methods, the list-iterator will throw a - * ConcurrentModificationException. Thus, in the face of + * {@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 next) + * 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 listIterator(int index) { - return new ListItr(index); + checkPositionIndex(index); + return new ListItr(index); } private class ListItr implements ListIterator { - private Entry lastReturned = header; - private Entry next; - private int nextIndex; - private int expectedModCount = modCount; - - ListItr(int index) { - if (index < 0 || index > size) - throw new IndexOutOfBoundsException("Index: "+index+ - ", Size: "+size); - if (index < (size >> 1)) { - next = header.next; - for (nextIndex=0; nextIndexindex; nextIndex--) - next = next.previous; - } - } - - public boolean hasNext() { - return nextIndex != size; - } - - public E next() { - checkForComodification(); - if (nextIndex == size) - throw new NoSuchElementException(); - - lastReturned = next; - next = next.next; - nextIndex++; - return lastReturned.element; - } - - public boolean hasPrevious() { - return nextIndex != 0; - } - - public E previous() { - if (nextIndex == 0) - throw new NoSuchElementException(); - - lastReturned = next = next.previous; - nextIndex--; - checkForComodification(); - return lastReturned.element; - } - - public int nextIndex() { - return nextIndex; - } - - public int previousIndex() { - return nextIndex-1; - } + private Node lastReturned = null; + private Node 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 void remove() { + public E previous() { checkForComodification(); - Entry lastNext = lastReturned.next; - try { - LinkedList.this.remove(lastReturned); - } catch (NoSuchElementException e) { + 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(); - } - if (next==lastReturned) + + Node lastNext = lastReturned.next; + unlink(lastReturned); + if (next == lastReturned) next = lastNext; else - nextIndex--; - lastReturned = header; - expectedModCount++; - } - - public void set(E e) { - if (lastReturned == header) - throw new IllegalStateException(); - checkForComodification(); - lastReturned.element = e; - } - - public void add(E e) { - checkForComodification(); - lastReturned = header; - addBefore(e, next); - nextIndex++; - expectedModCount++; - } - - final void checkForComodification() { - if (modCount != expectedModCount) - throw new ConcurrentModificationException(); - } - } - - private static class Entry { - E element; - Entry next; - Entry previous; - - Entry(E element, Entry next, Entry previous) { - this.element = element; - this.next = next; - this.previous = previous; - } - } - - private Entry addBefore(E e, Entry entry) { - Entry newEntry = new Entry(e, entry, entry.previous); - newEntry.previous.next = newEntry; - newEntry.next.previous = newEntry; - size++; - modCount++; - return newEntry; - } - - private E remove(Entry e) { - if (e == header) - throw new NoSuchElementException(); - - E result = e.element; - e.previous.next = e.next; - e.next.previous = e.previous; - e.next = e.previous = null; - e.element = null; - size--; - modCount++; - return result; + 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++; + } + + final void checkForComodification() { + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); + } + } + + private static class Node { + E item; + Node next; + Node prev; + + Node(Node prev, E element, Node next) { + this.item = element; + this.next = next; + this.prev = prev; + } + } + + /** + * @since 1.6 + */ + public Iterator descendingIterator() { + return new DescendingIterator(); + } + + /** + * Adapter to provide descending iterators via ListItr.previous + */ + private class DescendingIterator implements Iterator { + 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 superClone() { + try { + return (LinkedList) super.clone(); + } catch (CloneNotSupportedException e) { + throw new InternalError(); + } } /** - * Returns a shallow copy of this LinkedList. (The elements + * Returns a shallow copy of this {@code LinkedList}. (The elements * themselves are not cloned.) * - * @return a shallow copy of this LinkedList instance + * @return a shallow copy of this {@code LinkedList} instance */ public Object clone() { - LinkedList clone = null; - try { - clone = (LinkedList) super.clone(); - } catch (CloneNotSupportedException e) { - throw new InternalError(); - } + LinkedList clone = superClone(); // Put clone into "virgin" state - clone.header = new Entry(null, null, null); - clone.header.next = clone.header.previous = clone.header; + clone.first = clone.last = null; clone.size = 0; clone.modCount = 0; // Initialize clone with our elements - for (Entry e = header.next; e != header; e = e.next) - clone.add(e.element); + for (Node x = first; x != null; x = x.next) + clone.add(x.item); return clone; } @@ -827,7 +1026,7 @@ public class LinkedList *

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. - * + * *

This method acts as bridge between array-based and collection-based * APIs. * @@ -835,11 +1034,11 @@ public class LinkedList * in proper sequence */ public Object[] toArray() { - Object[] result = new Object[size]; + Object[] result = new Object[size]; int i = 0; - for (Entry e = header.next; e != header; e = e.next) - result[i++] = e.element; - return result; + for (Node x = first; x != null; x = x.next) + result[i++] = x.item; + return result; } /** @@ -852,7 +1051,7 @@ public class LinkedList * *

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 null. + * immediately following the end of the list is set to {@code null}. * (This is useful in determining the length of the list only if * the caller knows that the list does not contain any null elements.) * @@ -861,15 +1060,15 @@ public class LinkedList * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * - *

Suppose x is a list known to contain only strings. + *

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 String: + * allocated array of {@code String}: * *

      *     String[] y = x.toArray(new String[0]);
* - * Note that toArray(new Object[0]) is identical in function to - * toArray(). + * 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 @@ -880,14 +1079,15 @@ public class LinkedList * this list * @throws NullPointerException if the specified array is null */ + @SuppressWarnings("unchecked") public 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 (Entry e = header.next; e != header; e = e.next) - result[i++] = e.element; + Object[] result = a; + for (Node x = first; x != null; x = x.next) + result[i++] = x.item; if (a.length > size) a[size] = null; @@ -898,8 +1098,8 @@ public class LinkedList private static final long serialVersionUID = 876323262645176354L; /** - * Save the state of this LinkedList instance to a stream (that - * is, serialize it). + * 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 @@ -907,35 +1107,32 @@ public class LinkedList */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { - // Write out any hidden serialization magic - s.defaultWriteObject(); + // Write out any hidden serialization magic + s.defaultWriteObject(); // Write out size s.writeInt(size); - // Write out all elements in the proper order. - for (Entry e = header.next; e != header; e = e.next) - s.writeObject(e.element); + // Write out all elements in the proper order. + for (Node x = first; x != null; x = x.next) + s.writeObject(x.item); } /** - * Reconstitute this LinkedList instance from a stream (that is - * deserialize it). + * 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 any hidden serialization magic + s.defaultReadObject(); // Read in size int size = s.readInt(); - // Initialize header - header = new Entry(null, null, null); - header.next = header.previous = header; - - // Read in all elements in the proper order. - for (int i=0; i