提交 45d4a77f 编写于 作者: M martin

6897553: LinkedList performance improvements

Summary: LinkedList of size N creates N+1 instead of N+2 objects.  Comparing against null is faster than comparing against sentinel node
Reviewed-by: dl, jjb, forax
上级 1498ba76
...@@ -26,22 +26,22 @@ ...@@ -26,22 +26,22 @@
package java.util; package java.util;
/** /**
* Linked list implementation of the <tt>List</tt> interface. Implements all * Linked list implementation of the {@code List} interface. Implements all
* optional list operations, and permits all elements (including * optional list operations, and permits all elements (including
* <tt>null</tt>). In addition to implementing the <tt>List</tt> interface, * {@code null}). In addition to implementing the {@code List} interface,
* the <tt>LinkedList</tt> class provides uniformly named methods to * the {@code LinkedList} class provides uniformly named methods to
* <tt>get</tt>, <tt>remove</tt> and <tt>insert</tt> an element at the * {@code get}, {@code remove} and {@code insert} an element at the
* beginning and end of the list. These operations allow linked lists to be * beginning and end of the list. These operations allow linked lists to be
* used as a stack, {@linkplain Queue queue}, or {@linkplain Deque * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque
* double-ended queue}. <p> * double-ended queue}.
* *
* The class implements the <tt>Deque</tt> interface, providing * <p>The class implements the {@code Deque} interface, providing
* first-in-first-out queue operations for <tt>add</tt>, * first-in-first-out queue operations for {@code add},
* <tt>poll</tt>, along with other stack and deque operations.<p> * {@code poll}, along with other stack and deque operations.
* *
* All of the operations perform as could be expected for a doubly-linked * <p>All of the operations perform as could be expected for a doubly-linked
* list. Operations that index into the list will traverse the list from * list. Operations that index into the list will traverse the list from
* the beginning or the end, whichever is closer to the specified index.<p> * the beginning or the end, whichever is closer to the specified index.
* *
* <p><strong>Note that this implementation is not synchronized.</strong> * <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access a linked list concurrently, and at least * If multiple threads access a linked list concurrently, and at least
...@@ -58,11 +58,11 @@ package java.util; ...@@ -58,11 +58,11 @@ package java.util;
* unsynchronized access to the list:<pre> * unsynchronized access to the list:<pre>
* List list = Collections.synchronizedList(new LinkedList(...));</pre> * List list = Collections.synchronizedList(new LinkedList(...));</pre>
* *
* <p>The iterators returned by this class's <tt>iterator</tt> and * <p>The iterators returned by this class's {@code iterator} and
* <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is * {@code listIterator} methods are <i>fail-fast</i>: if the list is
* structurally modified at any time after the iterator is created, in * structurally modified at any time after the iterator is created, in
* any way except through the Iterator's own <tt>remove</tt> or * any way except through the Iterator's own {@code remove} or
* <tt>add</tt> methods, the iterator will throw a {@link * {@code add} methods, the iterator will throw a {@link
* ConcurrentModificationException}. Thus, in the face of concurrent * ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than * modification, the iterator fails quickly and cleanly, rather than
* risking arbitrary, non-deterministic behavior at an undetermined * risking arbitrary, non-deterministic behavior at an undetermined
...@@ -71,7 +71,7 @@ package java.util; ...@@ -71,7 +71,7 @@ package java.util;
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the * as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators * presence of unsynchronized concurrent modification. Fail-fast iterators
* throw <tt>ConcurrentModificationException</tt> 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 * Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators * exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i> * should be used only to detect bugs.</i>
...@@ -83,7 +83,6 @@ package java.util; ...@@ -83,7 +83,6 @@ package java.util;
* @author Josh Bloch * @author Josh Bloch
* @see List * @see List
* @see ArrayList * @see ArrayList
* @see Vector
* @since 1.2 * @since 1.2
* @param <E> the type of elements held in this collection * @param <E> the type of elements held in this collection
*/ */
...@@ -92,14 +91,26 @@ public class LinkedList<E> ...@@ -92,14 +91,26 @@ public class LinkedList<E>
extends AbstractSequentialList<E> extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{ {
private transient Entry<E> header = new Entry<E>(null, null, null); transient int size = 0;
private transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/** /**
* Constructs an empty list. * Constructs an empty list.
*/ */
public LinkedList() { public LinkedList() {
header.next = header.previous = header;
} }
/** /**
...@@ -115,6 +126,119 @@ public class LinkedList<E> ...@@ -115,6 +126,119 @@ public class LinkedList<E>
addAll(c); addAll(c);
} }
/**
* Links e as first element.
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<E>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<E>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<E>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
/**
* Unlinks non-null first node f.
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* Unlinks non-null last node l.
*/
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
/**
* Unlinks non-null node x.
*/
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
/** /**
* Returns the first element in this list. * Returns the first element in this list.
* *
...@@ -122,10 +246,10 @@ public class LinkedList<E> ...@@ -122,10 +246,10 @@ public class LinkedList<E>
* @throws NoSuchElementException if this list is empty * @throws NoSuchElementException if this list is empty
*/ */
public E getFirst() { public E getFirst() {
if (size==0) final Node<E> f = first;
if (f == null)
throw new NoSuchElementException(); throw new NoSuchElementException();
return f.item;
return header.next.element;
} }
/** /**
...@@ -135,10 +259,10 @@ public class LinkedList<E> ...@@ -135,10 +259,10 @@ public class LinkedList<E>
* @throws NoSuchElementException if this list is empty * @throws NoSuchElementException if this list is empty
*/ */
public E getLast() { public E getLast() {
if (size==0) final Node<E> l = last;
if (l == null)
throw new NoSuchElementException(); throw new NoSuchElementException();
return l.item;
return header.previous.element;
} }
/** /**
...@@ -148,7 +272,10 @@ public class LinkedList<E> ...@@ -148,7 +272,10 @@ public class LinkedList<E>
* @throws NoSuchElementException if this list is empty * @throws NoSuchElementException if this list is empty
*/ */
public E removeFirst() { public E removeFirst() {
return remove(header.next); final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
} }
/** /**
...@@ -158,7 +285,10 @@ public class LinkedList<E> ...@@ -158,7 +285,10 @@ public class LinkedList<E>
* @throws NoSuchElementException if this list is empty * @throws NoSuchElementException if this list is empty
*/ */
public E removeLast() { public E removeLast() {
return remove(header.previous); final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
} }
/** /**
...@@ -167,7 +297,7 @@ public class LinkedList<E> ...@@ -167,7 +297,7 @@ public class LinkedList<E>
* @param e the element to add * @param e the element to add
*/ */
public void addFirst(E e) { public void addFirst(E e) {
addBefore(e, header.next); linkFirst(e);
} }
/** /**
...@@ -178,17 +308,17 @@ public class LinkedList<E> ...@@ -178,17 +308,17 @@ public class LinkedList<E>
* @param e the element to add * @param e the element to add
*/ */
public void addLast(E e) { public void addLast(E e) {
addBefore(e, header); linkLast(e);
} }
/** /**
* Returns <tt>true</tt> if this list contains the specified element. * Returns {@code true} if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains * More formally, returns {@code true} if and only if this list contains
* at least one element <tt>e</tt> such that * at least one element {@code e} such that
* <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
* *
* @param o element whose presence in this list is to be tested * @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element * @return {@code true} if this list contains the specified element
*/ */
public boolean contains(Object o) { public boolean contains(Object o) {
return indexOf(o) != -1; return indexOf(o) != -1;
...@@ -209,10 +339,10 @@ public class LinkedList<E> ...@@ -209,10 +339,10 @@ public class LinkedList<E>
* <p>This method is equivalent to {@link #addLast}. * <p>This method is equivalent to {@link #addLast}.
* *
* @param e element to be appended to this list * @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add}) * @return {@code true} (as specified by {@link Collection#add})
*/ */
public boolean add(E e) { public boolean add(E e) {
addBefore(e, header); linkLast(e);
return true; return true;
} }
...@@ -220,27 +350,27 @@ public class LinkedList<E> ...@@ -220,27 +350,27 @@ public class LinkedList<E>
* Removes the first occurrence of the specified element from this list, * 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 * if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index * unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that * {@code i} such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list * (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list * contained the specified element (or equivalently, if this list
* changed as a result of the call). * changed as a result of the call).
* *
* @param o element to be removed from this list, if present * @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element * @return {@code true} if this list contained the specified element
*/ */
public boolean remove(Object o) { public boolean remove(Object o) {
if (o==null) { if (o == null) {
for (Entry<E> e = header.next; e != header; e = e.next) { for (Node<E> x = first; x != null; x = x.next) {
if (e.element==null) { if (x.item == null) {
remove(e); unlink(x);
return true; return true;
} }
} }
} else { } else {
for (Entry<E> e = header.next; e != header; e = e.next) { for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(e.element)) { if (o.equals(x.item)) {
remove(e); unlink(x);
return true; return true;
} }
} }
...@@ -257,7 +387,7 @@ public class LinkedList<E> ...@@ -257,7 +387,7 @@ public class LinkedList<E>
* this list, and it's nonempty.) * this list, and it's nonempty.)
* *
* @param c collection containing elements to be added to this list * @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call * @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null * @throws NullPointerException if the specified collection is null
*/ */
public boolean addAll(Collection<? extends E> c) { public boolean addAll(Collection<? extends E> c) {
...@@ -275,45 +405,66 @@ public class LinkedList<E> ...@@ -275,45 +405,66 @@ public class LinkedList<E>
* @param index index at which to insert the first element * @param index index at which to insert the first element
* from the specified collection * from the specified collection
* @param c collection containing elements to be added to this list * @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call * @return {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null * @throws NullPointerException if the specified collection is null
*/ */
public boolean addAll(int index, Collection<? extends E> c) { public boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > size) checkPositionIndex(index);
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Object[] a = c.toArray(); Object[] a = c.toArray();
int numNew = a.length; int numNew = a.length;
if (numNew==0) if (numNew == 0)
return false; return false;
modCount++;
Entry<E> successor = (index==size ? header : entry(index)); Node<E> pred, succ;
Entry<E> predecessor = successor.previous; if (index == size) {
for (int i=0; i<numNew; i++) { succ = null;
Entry<E> e = new Entry<E>((E)a[i], successor, predecessor); pred = last;
predecessor.next = e; } else {
predecessor = e; succ = node(index);
pred = succ.prev;
}
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<E>(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; size += numNew;
modCount++;
return true; return true;
} }
/** /**
* Removes all of the elements from this list. * Removes all of the elements from this list.
* The list will be empty after this call returns.
*/ */
public void clear() { public void clear() {
Entry<E> e = header.next; // Clearing all of the links between nodes is "unnecessary", but:
while (e != header) { // - helps a generational GC if the discarded nodes inhabit
Entry<E> next = e.next; // more than one generation
e.next = e.previous = null; // - is sure to free memory even if there is a reachable Iterator
e.element = null; for (Node<E> x = first; x != null; ) {
e = next; Node<E> next = x.next;
} x.item = null;
header.next = header.previous = header; x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0; size = 0;
modCount++; modCount++;
} }
...@@ -329,7 +480,8 @@ public class LinkedList<E> ...@@ -329,7 +480,8 @@ public class LinkedList<E>
* @throws IndexOutOfBoundsException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc}
*/ */
public E get(int index) { public E get(int index) {
return entry(index).element; checkElementIndex(index);
return node(index).item;
} }
/** /**
...@@ -342,9 +494,10 @@ public class LinkedList<E> ...@@ -342,9 +494,10 @@ public class LinkedList<E>
* @throws IndexOutOfBoundsException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc}
*/ */
public E set(int index, E element) { public E set(int index, E element) {
Entry<E> e = entry(index); checkElementIndex(index);
E oldVal = e.element; Node<E> x = node(index);
e.element = element; E oldVal = x.item;
x.item = element;
return oldVal; return oldVal;
} }
...@@ -358,7 +511,12 @@ public class LinkedList<E> ...@@ -358,7 +511,12 @@ public class LinkedList<E>
* @throws IndexOutOfBoundsException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc}
*/ */
public void add(int index, E element) { 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));
} }
/** /**
...@@ -371,34 +529,69 @@ public class LinkedList<E> ...@@ -371,34 +529,69 @@ public class LinkedList<E>
* @throws IndexOutOfBoundsException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc}
*/ */
public E remove(int index) { 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;
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
} }
/** /**
* Returns the indexed entry. * Returns the (non-null) Node at the specified element index.
*/ */
private Entry<E> entry(int index) { Node<E> node(int index) {
if (index < 0 || index >= size) // assert isElementIndex(index);
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) { if (index < (size >> 1)) {
for (int i = 0; i <= index; i++) Node<E> x = first;
e = e.next; for (int i = 0; i < index; i++)
x = x.next;
return x;
} else { } else {
for (int i = size; i > index; i--) Node<E> x = last;
e = e.previous; for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
} }
return e;
} }
// Search Operations // Search Operations
/** /**
* Returns the index of the first occurrence of the specified element * Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element. * in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that * More formally, returns the lowest index {@code i} such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index. * or -1 if there is no such index.
* *
...@@ -408,15 +601,15 @@ public class LinkedList<E> ...@@ -408,15 +601,15 @@ public class LinkedList<E>
*/ */
public int indexOf(Object o) { public int indexOf(Object o) {
int index = 0; int index = 0;
if (o==null) { if (o == null) {
for (Entry e = header.next; e != header; e = e.next) { for (Node<E> x = first; x != null; x = x.next) {
if (e.element==null) if (x.item == null)
return index; return index;
index++; index++;
} }
} else { } else {
for (Entry e = header.next; e != header; e = e.next) { for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(e.element)) if (o.equals(x.item))
return index; return index;
index++; index++;
} }
...@@ -427,7 +620,7 @@ public class LinkedList<E> ...@@ -427,7 +620,7 @@ public class LinkedList<E>
/** /**
* Returns the index of the last occurrence of the specified element * Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element. * in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that * More formally, returns the highest index {@code i} such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index. * or -1 if there is no such index.
* *
...@@ -437,16 +630,16 @@ public class LinkedList<E> ...@@ -437,16 +630,16 @@ public class LinkedList<E>
*/ */
public int lastIndexOf(Object o) { public int lastIndexOf(Object o) {
int index = size; int index = size;
if (o==null) { if (o == null) {
for (Entry e = header.previous; e != header; e = e.previous) { for (Node<E> x = last; x != null; x = x.prev) {
index--; index--;
if (e.element==null) if (x.item == null)
return index; return index;
} }
} else { } else {
for (Entry e = header.previous; e != header; e = e.previous) { for (Node<E> x = last; x != null; x = x.prev) {
index--; index--;
if (o.equals(e.element)) if (o.equals(x.item))
return index; return index;
} }
} }
...@@ -457,17 +650,18 @@ public class LinkedList<E> ...@@ -457,17 +650,18 @@ public class LinkedList<E>
/** /**
* Retrieves, but does not remove, the head (first element) of this list. * Retrieves, but does not remove, the head (first element) of this list.
* @return the head of this list, or <tt>null</tt> if this list is empty *
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5 * @since 1.5
*/ */
public E peek() { public E peek() {
if (size==0) final Node<E> f = first;
return null; return (f == null) ? null : f.item;
return getFirst();
} }
/** /**
* Retrieves, but does not remove, the head (first element) of this list. * Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list * @return the head of this list
* @throws NoSuchElementException if this list is empty * @throws NoSuchElementException if this list is empty
* @since 1.5 * @since 1.5
...@@ -477,14 +671,14 @@ public class LinkedList<E> ...@@ -477,14 +671,14 @@ public class LinkedList<E>
} }
/** /**
* Retrieves and removes the head (first element) of this list * Retrieves and removes the head (first element) of this list.
* @return the head of this list, or <tt>null</tt> if this list is empty *
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5 * @since 1.5
*/ */
public E poll() { public E poll() {
if (size==0) final Node<E> f = first;
return null; return (f == null) ? null : unlinkFirst(f);
return removeFirst();
} }
/** /**
...@@ -502,7 +696,7 @@ public class LinkedList<E> ...@@ -502,7 +696,7 @@ public class LinkedList<E>
* Adds the specified element as the tail (last element) of this list. * Adds the specified element as the tail (last element) of this list.
* *
* @param e the element to add * @param e the element to add
* @return <tt>true</tt> (as specified by {@link Queue#offer}) * @return {@code true} (as specified by {@link Queue#offer})
* @since 1.5 * @since 1.5
*/ */
public boolean offer(E e) { public boolean offer(E e) {
...@@ -514,7 +708,7 @@ public class LinkedList<E> ...@@ -514,7 +708,7 @@ public class LinkedList<E>
* Inserts the specified element at the front of this list. * Inserts the specified element at the front of this list.
* *
* @param e the element to insert * @param e the element to insert
* @return <tt>true</tt> (as specified by {@link Deque#offerFirst}) * @return {@code true} (as specified by {@link Deque#offerFirst})
* @since 1.6 * @since 1.6
*/ */
public boolean offerFirst(E e) { public boolean offerFirst(E e) {
...@@ -526,7 +720,7 @@ public class LinkedList<E> ...@@ -526,7 +720,7 @@ public class LinkedList<E>
* Inserts the specified element at the end of this list. * Inserts the specified element at the end of this list.
* *
* @param e the element to insert * @param e the element to insert
* @return <tt>true</tt> (as specified by {@link Deque#offerLast}) * @return {@code true} (as specified by {@link Deque#offerLast})
* @since 1.6 * @since 1.6
*/ */
public boolean offerLast(E e) { public boolean offerLast(E e) {
...@@ -536,58 +730,54 @@ public class LinkedList<E> ...@@ -536,58 +730,54 @@ public class LinkedList<E>
/** /**
* Retrieves, but does not remove, the first element of this list, * Retrieves, but does not remove, the first element of this list,
* or returns <tt>null</tt> if this list is empty. * or returns {@code null} if this list is empty.
* *
* @return the first element of this list, or <tt>null</tt> * @return the first element of this list, or {@code null}
* if this list is empty * if this list is empty
* @since 1.6 * @since 1.6
*/ */
public E peekFirst() { public E peekFirst() {
if (size==0) final Node<E> f = first;
return null; return (f == null) ? null : f.item;
return getFirst();
} }
/** /**
* Retrieves, but does not remove, the last element of this list, * Retrieves, but does not remove, the last element of this list,
* or returns <tt>null</tt> if this list is empty. * or returns {@code null} if this list is empty.
* *
* @return the last element of this list, or <tt>null</tt> * @return the last element of this list, or {@code null}
* if this list is empty * if this list is empty
* @since 1.6 * @since 1.6
*/ */
public E peekLast() { public E peekLast() {
if (size==0) final Node<E> l = last;
return null; return (l == null) ? null : l.item;
return getLast();
} }
/** /**
* Retrieves and removes the first element of this list, * Retrieves and removes the first element of this list,
* or returns <tt>null</tt> if this list is empty. * or returns {@code null} if this list is empty.
* *
* @return the first element of this list, or <tt>null</tt> if * @return the first element of this list, or {@code null} if
* this list is empty * this list is empty
* @since 1.6 * @since 1.6
*/ */
public E pollFirst() { public E pollFirst() {
if (size==0) final Node<E> f = first;
return null; return (f == null) ? null : unlinkFirst(f);
return removeFirst();
} }
/** /**
* Retrieves and removes the last element of this list, * Retrieves and removes the last element of this list,
* or returns <tt>null</tt> if this list is empty. * or returns {@code null} if this list is empty.
* *
* @return the last element of this list, or <tt>null</tt> if * @return the last element of this list, or {@code null} if
* this list is empty * this list is empty
* @since 1.6 * @since 1.6
*/ */
public E pollLast() { public E pollLast() {
if (size==0) final Node<E> l = last;
return null; return (l == null) ? null : unlinkLast(l);
return removeLast();
} }
/** /**
...@@ -624,7 +814,7 @@ public class LinkedList<E> ...@@ -624,7 +814,7 @@ public class LinkedList<E>
* does not contain the element, it is unchanged. * does not contain the element, it is unchanged.
* *
* @param o element to be removed from this list, if present * @param o element to be removed from this list, if present
* @return <tt>true</tt> if the list contained the specified element * @return {@code true} if the list contained the specified element
* @since 1.6 * @since 1.6
*/ */
public boolean removeFirstOccurrence(Object o) { public boolean removeFirstOccurrence(Object o) {
...@@ -637,21 +827,21 @@ public class LinkedList<E> ...@@ -637,21 +827,21 @@ public class LinkedList<E>
* does not contain the element, it is unchanged. * does not contain the element, it is unchanged.
* *
* @param o element to be removed from this list, if present * @param o element to be removed from this list, if present
* @return <tt>true</tt> if the list contained the specified element * @return {@code true} if the list contained the specified element
* @since 1.6 * @since 1.6
*/ */
public boolean removeLastOccurrence(Object o) { public boolean removeLastOccurrence(Object o) {
if (o==null) { if (o == null) {
for (Entry<E> e = header.previous; e != header; e = e.previous) { for (Node<E> x = last; x != null; x = x.prev) {
if (e.element==null) { if (x.item == null) {
remove(e); unlink(x);
return true; return true;
} }
} }
} else { } else {
for (Entry<E> e = header.previous; e != header; e = e.previous) { for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(e.element)) { if (o.equals(x.item)) {
remove(e); unlink(x);
return true; return true;
} }
} }
...@@ -662,76 +852,68 @@ public class LinkedList<E> ...@@ -662,76 +852,68 @@ public class LinkedList<E>
/** /**
* Returns a list-iterator of the elements in this list (in proper * Returns a list-iterator of the elements in this list (in proper
* sequence), starting at the specified position in the list. * sequence), starting at the specified position in the list.
* Obeys the general contract of <tt>List.listIterator(int)</tt>.<p> * Obeys the general contract of {@code List.listIterator(int)}.<p>
* *
* The list-iterator is <i>fail-fast</i>: if the list is structurally * The list-iterator is <i>fail-fast</i>: if the list is structurally
* modified at any time after the Iterator is created, in any way except * modified at any time after the Iterator is created, in any way except
* through the list-iterator's own <tt>remove</tt> or <tt>add</tt> * through the list-iterator's own {@code remove} or {@code add}
* methods, the list-iterator will throw a * methods, the list-iterator will throw a
* <tt>ConcurrentModificationException</tt>. Thus, in the face of * {@code ConcurrentModificationException}. Thus, in the face of
* concurrent modification, the iterator fails quickly and cleanly, rather * concurrent modification, the iterator fails quickly and cleanly, rather
* than risking arbitrary, non-deterministic behavior at an undetermined * than risking arbitrary, non-deterministic behavior at an undetermined
* time in the future. * time in the future.
* *
* @param index index of the first element to be returned from the * @param index index of the first element to be returned from the
* list-iterator (by a call to <tt>next</tt>) * list-iterator (by a call to {@code next})
* @return a ListIterator of the elements in this list (in proper * @return a ListIterator of the elements in this list (in proper
* sequence), starting at the specified position in the list * sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc}
* @see List#listIterator(int) * @see List#listIterator(int)
*/ */
public ListIterator<E> listIterator(int index) { public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index); return new ListItr(index);
} }
private class ListItr implements ListIterator<E> { private class ListItr implements ListIterator<E> {
private Entry<E> lastReturned = header; private Node<E> lastReturned = null;
private Entry<E> next; private Node<E> next;
private int nextIndex; private int nextIndex;
private int expectedModCount = modCount; private int expectedModCount = modCount;
ListItr(int index) { ListItr(int index) {
if (index < 0 || index > size) // assert isPositionIndex(index);
throw new IndexOutOfBoundsException("Index: "+index+ next = (index == size) ? null : node(index);
", Size: "+size); nextIndex = index;
if (index < (size >> 1)) {
next = header.next;
for (nextIndex=0; nextIndex<index; nextIndex++)
next = next.next;
} else {
next = header;
for (nextIndex=size; nextIndex>index; nextIndex--)
next = next.previous;
}
} }
public boolean hasNext() { public boolean hasNext() {
return nextIndex != size; return nextIndex < size;
} }
public E next() { public E next() {
checkForComodification(); checkForComodification();
if (nextIndex == size) if (!hasNext())
throw new NoSuchElementException(); throw new NoSuchElementException();
lastReturned = next; lastReturned = next;
next = next.next; next = next.next;
nextIndex++; nextIndex++;
return lastReturned.element; return lastReturned.item;
} }
public boolean hasPrevious() { public boolean hasPrevious() {
return nextIndex != 0; return nextIndex > 0;
} }
public E previous() { public E previous() {
if (nextIndex == 0) checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException(); throw new NoSuchElementException();
lastReturned = next = next.previous; lastReturned = next = (next == null) ? last : next.prev;
nextIndex--; nextIndex--;
checkForComodification(); return lastReturned.item;
return lastReturned.element;
} }
public int nextIndex() { public int nextIndex() {
...@@ -739,36 +921,38 @@ public class LinkedList<E> ...@@ -739,36 +921,38 @@ public class LinkedList<E>
} }
public int previousIndex() { public int previousIndex() {
return nextIndex-1; return nextIndex - 1;
} }
public void remove() { public void remove() {
checkForComodification(); checkForComodification();
Entry<E> lastNext = lastReturned.next; if (lastReturned == null)
try {
LinkedList.this.remove(lastReturned);
} catch (NoSuchElementException e) {
throw new IllegalStateException(); throw new IllegalStateException();
}
if (next==lastReturned) Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext; next = lastNext;
else else
nextIndex--; nextIndex--;
lastReturned = header; lastReturned = null;
expectedModCount++; expectedModCount++;
} }
public void set(E e) { public void set(E e) {
if (lastReturned == header) if (lastReturned == null)
throw new IllegalStateException(); throw new IllegalStateException();
checkForComodification(); checkForComodification();
lastReturned.element = e; lastReturned.item = e;
} }
public void add(E e) { public void add(E e) {
checkForComodification(); checkForComodification();
lastReturned = header; lastReturned = null;
addBefore(e, next); if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++; nextIndex++;
expectedModCount++; expectedModCount++;
} }
...@@ -779,41 +963,18 @@ public class LinkedList<E> ...@@ -779,41 +963,18 @@ public class LinkedList<E>
} }
} }
private static class Entry<E> { private static class Node<E> {
E element; E item;
Entry<E> next; Node<E> next;
Entry<E> previous; Node<E> prev;
Entry(E element, Entry<E> next, Entry<E> previous) { Node(Node<E> prev, E element, Node<E> next) {
this.element = element; this.item = element;
this.next = next; this.next = next;
this.previous = previous; this.prev = prev;
} }
} }
private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
private E remove(Entry<E> 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;
}
/** /**
* @since 1.6 * @since 1.6
*/ */
...@@ -821,9 +982,11 @@ public class LinkedList<E> ...@@ -821,9 +982,11 @@ public class LinkedList<E>
return new DescendingIterator(); return new DescendingIterator();
} }
/** Adapter to provide descending iterators via ListItr.previous */ /**
private class DescendingIterator implements Iterator { * Adapter to provide descending iterators via ListItr.previous
final ListItr itr = new ListItr(size()); */
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() { public boolean hasNext() {
return itr.hasPrevious(); return itr.hasPrevious();
} }
...@@ -835,29 +998,32 @@ public class LinkedList<E> ...@@ -835,29 +998,32 @@ public class LinkedList<E>
} }
} }
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/** /**
* Returns a shallow copy of this <tt>LinkedList</tt>. (The elements * Returns a shallow copy of this {@code LinkedList}. (The elements
* themselves are not cloned.) * themselves are not cloned.)
* *
* @return a shallow copy of this <tt>LinkedList</tt> instance * @return a shallow copy of this {@code LinkedList} instance
*/ */
public Object clone() { public Object clone() {
LinkedList<E> clone = null; LinkedList<E> clone = superClone();
try {
clone = (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
// Put clone into "virgin" state // Put clone into "virgin" state
clone.header = new Entry<E>(null, null, null); clone.first = clone.last = null;
clone.header.next = clone.header.previous = clone.header;
clone.size = 0; clone.size = 0;
clone.modCount = 0; clone.modCount = 0;
// Initialize clone with our elements // Initialize clone with our elements
for (Entry<E> e = header.next; e != header; e = e.next) for (Node<E> x = first; x != null; x = x.next)
clone.add(e.element); clone.add(x.item);
return clone; return clone;
} }
...@@ -879,8 +1045,8 @@ public class LinkedList<E> ...@@ -879,8 +1045,8 @@ public class LinkedList<E>
public Object[] toArray() { public Object[] toArray() {
Object[] result = new Object[size]; Object[] result = new Object[size];
int i = 0; int i = 0;
for (Entry<E> e = header.next; e != header; e = e.next) for (Node<E> x = first; x != null; x = x.next)
result[i++] = e.element; result[i++] = x.item;
return result; return result;
} }
...@@ -894,7 +1060,7 @@ public class LinkedList<E> ...@@ -894,7 +1060,7 @@ public class LinkedList<E>
* *
* <p>If the list fits in the specified array with room to spare (i.e., * <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array * the array has more elements than the list), the element in the array
* immediately following the end of the list is set to <tt>null</tt>. * immediately following the end of the list is set to {@code null}.
* (This is useful in determining the length of the list <i>only</i> if * (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any null elements.) * the caller knows that the list does not contain any null elements.)
* *
...@@ -903,15 +1069,15 @@ public class LinkedList<E> ...@@ -903,15 +1069,15 @@ public class LinkedList<E>
* precise control over the runtime type of the output array, and may, * precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs. * under certain circumstances, be used to save allocation costs.
* *
* <p>Suppose <tt>x</tt> is a list known to contain only strings. * <p>Suppose {@code x} is a list known to contain only strings.
* The following code can be used to dump the list into a newly * The following code can be used to dump the list into a newly
* allocated array of <tt>String</tt>: * allocated array of {@code String}:
* *
* <pre> * <pre>
* String[] y = x.toArray(new String[0]);</pre> * String[] y = x.toArray(new String[0]);</pre>
* *
* Note that <tt>toArray(new Object[0])</tt> is identical in function to * Note that {@code toArray(new Object[0])} is identical in function to
* <tt>toArray()</tt>. * {@code toArray()}.
* *
* @param a the array into which the elements of the list are to * @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 * be stored, if it is big enough; otherwise, a new array of the
...@@ -922,14 +1088,15 @@ public class LinkedList<E> ...@@ -922,14 +1088,15 @@ public class LinkedList<E>
* this list * this list
* @throws NullPointerException if the specified array is null * @throws NullPointerException if the specified array is null
*/ */
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) { public <T> T[] toArray(T[] a) {
if (a.length < size) if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance( a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size); a.getClass().getComponentType(), size);
int i = 0; int i = 0;
Object[] result = a; Object[] result = a;
for (Entry<E> e = header.next; e != header; e = e.next) for (Node<E> x = first; x != null; x = x.next)
result[i++] = e.element; result[i++] = x.item;
if (a.length > size) if (a.length > size)
a[size] = null; a[size] = null;
...@@ -940,8 +1107,8 @@ public class LinkedList<E> ...@@ -940,8 +1107,8 @@ public class LinkedList<E>
private static final long serialVersionUID = 876323262645176354L; private static final long serialVersionUID = 876323262645176354L;
/** /**
* Save the state of this <tt>LinkedList</tt> instance to a stream (that * Saves the state of this {@code LinkedList} instance to a stream
* is, serialize it). * (that is, serializes it).
* *
* @serialData The size of the list (the number of elements it * @serialData The size of the list (the number of elements it
* contains) is emitted (int), followed by all of its * contains) is emitted (int), followed by all of its
...@@ -956,14 +1123,15 @@ public class LinkedList<E> ...@@ -956,14 +1123,15 @@ public class LinkedList<E>
s.writeInt(size); s.writeInt(size);
// Write out all elements in the proper order. // Write out all elements in the proper order.
for (Entry e = header.next; e != header; e = e.next) for (Node<E> x = first; x != null; x = x.next)
s.writeObject(e.element); s.writeObject(x.item);
} }
/** /**
* Reconstitute this <tt>LinkedList</tt> instance from a stream (that is * Reconstitutes this {@code LinkedList} instance from a stream
* deserialize it). * (that is, deserializes it).
*/ */
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s) private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException { throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic // Read in any hidden serialization magic
...@@ -972,12 +1140,8 @@ public class LinkedList<E> ...@@ -972,12 +1140,8 @@ public class LinkedList<E>
// Read in size // Read in size
int size = s.readInt(); int size = s.readInt();
// Initialize header
header = new Entry<E>(null, null, null);
header.next = header.previous = header;
// Read in all elements in the proper order. // Read in all elements in the proper order.
for (int i=0; i<size; i++) for (int i = 0; i < size; i++)
addBefore((E)s.readObject(), header); linkLast((E)s.readObject());
} }
} }
...@@ -421,8 +421,11 @@ public class MOAT { ...@@ -421,8 +421,11 @@ public class MOAT {
private static void testQueue(Queue<Integer> q) { private static void testQueue(Queue<Integer> q) {
q.clear(); q.clear();
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++) {
testQueueAddRemove(q, null);
testQueueAddRemove(q, 537);
q.add(i); q.add(i);
}
equal(q.size(), 5); equal(q.size(), 5);
checkFunctionalInvariants(q); checkFunctionalInvariants(q);
q.poll(); q.poll();
...@@ -435,6 +438,216 @@ public class MOAT { ...@@ -435,6 +438,216 @@ public class MOAT {
} }
} }
private static void testQueueAddRemove(final Queue<Integer> q,
final Integer e) {
final List<Integer> originalContents = new ArrayList<Integer>(q);
final boolean isEmpty = q.isEmpty();
final boolean isList = (q instanceof List);
final List asList = isList ? (List) q : null;
check(!q.contains(e));
try {
q.add(e);
} catch (NullPointerException npe) {
check(e == null);
return; // Null elements not supported
}
check(q.contains(e));
check(q.remove(e));
check(!q.contains(e));
equal(new ArrayList<Integer>(q), originalContents);
if (q instanceof Deque<?>) {
final Deque<Integer> deq = (Deque<Integer>) q;
final List<Integer> singleton = Collections.singletonList(e);
// insert, query, remove element at head
if (isEmpty) {
THROWS(NoSuchElementException.class,
new Fun(){void f(){ deq.getFirst(); }},
new Fun(){void f(){ deq.element(); }},
new Fun(){void f(){ deq.iterator().next(); }});
check(deq.peekFirst() == null);
check(deq.peek() == null);
} else {
check(deq.getFirst() != e);
check(deq.element() != e);
check(deq.iterator().next() != e);
check(deq.peekFirst() != e);
check(deq.peek() != e);
}
check(!deq.contains(e));
check(!deq.removeFirstOccurrence(e));
check(!deq.removeLastOccurrence(e));
if (isList) {
check(asList.indexOf(e) == -1);
check(asList.lastIndexOf(e) == -1);
}
switch (rnd.nextInt(isList ? 4 : 3)) {
case 0: deq.addFirst(e); break;
case 1: check(deq.offerFirst(e)); break;
case 2: deq.push(e); break;
case 3: asList.add(0, e); break;
default: throw new AssertionError();
}
check(deq.peekFirst() == e);
check(deq.getFirst() == e);
check(deq.element() == e);
check(deq.peek() == e);
check(deq.iterator().next() == e);
check(deq.contains(e));
if (isList) {
check(asList.get(0) == e);
check(asList.indexOf(e) == 0);
check(asList.lastIndexOf(e) == 0);
check(asList.subList(0, 1).equals(singleton));
}
switch (rnd.nextInt(isList ? 11 : 9)) {
case 0: check(deq.pollFirst() == e); break;
case 1: check(deq.removeFirst() == e); break;
case 2: check(deq.remove() == e); break;
case 3: check(deq.pop() == e); break;
case 4: check(deq.removeFirstOccurrence(e)); break;
case 5: check(deq.removeLastOccurrence(e)); break;
case 6: check(deq.remove(e)); break;
case 7: check(deq.removeAll(singleton)); break;
case 8: Iterator it = deq.iterator(); it.next(); it.remove(); break;
case 9: asList.remove(0); break;
case 10: asList.subList(0, 1).clear(); break;
default: throw new AssertionError();
}
if (isEmpty) {
THROWS(NoSuchElementException.class,
new Fun(){void f(){ deq.getFirst(); }},
new Fun(){void f(){ deq.element(); }},
new Fun(){void f(){ deq.iterator().next(); }});
check(deq.peekFirst() == null);
check(deq.peek() == null);
} else {
check(deq.getFirst() != e);
check(deq.element() != e);
check(deq.iterator().next() != e);
check(deq.peekFirst() != e);
check(deq.peek() != e);
}
check(!deq.contains(e));
check(!deq.removeFirstOccurrence(e));
check(!deq.removeLastOccurrence(e));
if (isList) {
check(isEmpty || asList.get(0) != e);
check(asList.indexOf(e) == -1);
check(asList.lastIndexOf(e) == -1);
}
equal(new ArrayList<Integer>(deq), originalContents);
// insert, query, remove element at tail
if (isEmpty) {
check(deq.peekLast() == null);
THROWS(NoSuchElementException.class,
new Fun(){void f(){ deq.getLast(); }});
} else {
check(deq.peekLast() != e);
check(deq.getLast() != e);
}
switch (rnd.nextInt(isList ? 6 : 4)) {
case 0: deq.addLast(e); break;
case 1: check(deq.offerLast(e)); break;
case 2: check(deq.add(e)); break;
case 3: deq.addAll(singleton); break;
case 4: asList.addAll(deq.size(), singleton); break;
case 5: asList.add(deq.size(), e); break;
default: throw new AssertionError();
}
check(deq.peekLast() == e);
check(deq.getLast() == e);
check(deq.contains(e));
if (isList) {
ListIterator it = asList.listIterator(asList.size());
check(it.previous() == e);
check(asList.get(asList.size() - 1) == e);
check(asList.indexOf(e) == asList.size() - 1);
check(asList.lastIndexOf(e) == asList.size() - 1);
int size = asList.size();
check(asList.subList(size - 1, size).equals(singleton));
}
switch (rnd.nextInt(isList ? 8 : 6)) {
case 0: check(deq.pollLast() == e); break;
case 1: check(deq.removeLast() == e); break;
case 2: check(deq.removeFirstOccurrence(e)); break;
case 3: check(deq.removeLastOccurrence(e)); break;
case 4: check(deq.remove(e)); break;
case 5: check(deq.removeAll(singleton)); break;
case 6: asList.remove(asList.size() - 1); break;
case 7:
ListIterator it = asList.listIterator(asList.size());
it.previous();
it.remove();
break;
default: throw new AssertionError();
}
if (isEmpty) {
check(deq.peekLast() == null);
THROWS(NoSuchElementException.class,
new Fun(){void f(){ deq.getLast(); }});
} else {
check(deq.peekLast() != e);
check(deq.getLast() != e);
}
check(!deq.contains(e));
equal(new ArrayList<Integer>(deq), originalContents);
// Test operations on empty deque
switch (rnd.nextInt(isList ? 4 : 2)) {
case 0: deq.clear(); break;
case 1:
Iterator it = deq.iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
break;
case 2: asList.subList(0, asList.size()).clear(); break;
case 3:
ListIterator lit = asList.listIterator(asList.size());
while (lit.hasPrevious()) {
lit.previous();
lit.remove();
}
break;
default: throw new AssertionError();
}
testEmptyCollection(deq);
check(!deq.iterator().hasNext());
if (isList) {
check(!asList.listIterator().hasPrevious());
THROWS(NoSuchElementException.class,
new Fun(){void f(){ asList.listIterator().previous(); }});
}
THROWS(NoSuchElementException.class,
new Fun(){void f(){ deq.iterator().next(); }},
new Fun(){void f(){ deq.element(); }},
new Fun(){void f(){ deq.getFirst(); }},
new Fun(){void f(){ deq.getLast(); }},
new Fun(){void f(){ deq.pop(); }},
new Fun(){void f(){ deq.remove(); }},
new Fun(){void f(){ deq.removeFirst(); }},
new Fun(){void f(){ deq.removeLast(); }});
check(deq.poll() == null);
check(deq.pollFirst() == null);
check(deq.pollLast() == null);
check(deq.peek() == null);
check(deq.peekFirst() == null);
check(deq.peekLast() == null);
check(!deq.removeFirstOccurrence(e));
check(!deq.removeLastOccurrence(e));
check(deq.addAll(originalContents) == !isEmpty);
equal(new ArrayList<Integer>(deq), originalContents);
check(!deq.addAll(Collections.<Integer>emptyList()));
equal(new ArrayList<Integer>(deq), originalContents);
}
}
private static void testQueueIteratorRemove(Queue<Integer> q) { private static void testQueueIteratorRemove(Queue<Integer> q) {
System.err.printf("testQueueIteratorRemove %s%n", System.err.printf("testQueueIteratorRemove %s%n",
q.getClass().getSimpleName()); q.getClass().getSimpleName());
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册