--- jsr166/src/main/java/util/ArrayDeque.java 2013/02/11 07:42:43 1.46
+++ jsr166/src/main/java/util/ArrayDeque.java 2015/10/11 00:50:06 1.73
@@ -1,13 +1,11 @@
/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
+ * Written by Josh Bloch of Google Inc. and released to the public domain,
+ * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
*/
package java.util;
-import java.util.Spliterator;
-import java.util.stream.Stream;
-import java.util.stream.Streams;
+
+import java.io.Serializable;
import java.util.function.Consumer;
/**
@@ -20,16 +18,18 @@ import java.util.function.Consumer;
* when used as a queue.
*
*
Most {@code ArrayDeque} operations run in amortized constant time.
- * Exceptions include {@link #remove(Object) remove}, {@link
- * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
- * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
- * iterator.remove()}, and the bulk operations, all of which run in linear
- * time.
+ * Exceptions include
+ * {@link #remove(Object) remove},
+ * {@link #removeFirstOccurrence removeFirstOccurrence},
+ * {@link #removeLastOccurrence removeLastOccurrence},
+ * {@link #contains contains},
+ * {@link #iterator iterator.remove()},
+ * and the bulk operations, all of which run in linear time.
*
- *
The iterators returned by this class's {@code iterator} method are
- * fail-fast: If the deque is modified at any time after the iterator
- * is created, in any way except through the iterator's own {@code remove}
- * method, the iterator will generally throw a {@link
+ *
The iterators returned by this class's {@link #iterator() iterator}
+ * method are fail-fast: If the deque is modified at any time after
+ * the iterator is created, in any way except through the iterator's own
+ * {@code remove} method, the iterator will generally throw a {@link
* ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
@@ -53,10 +53,10 @@ import java.util.function.Consumer;
*
* @author Josh Bloch and Doug Lea
* @since 1.6
- * @param the type of elements held in this collection
+ * @param the type of elements held in this deque
*/
public class ArrayDeque extends AbstractCollection
- implements Deque, Cloneable, java.io.Serializable
+ implements Deque, Cloneable, Serializable
{
/**
* The array in which the elements of the deque are stored.
@@ -109,8 +109,8 @@ public class ArrayDeque extends Abstr
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
- if (initialCapacity < 0) // Too many elements, must back off
- initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
+ if (initialCapacity < 0) // Too many elements, must back off
+ initialCapacity >>>= 1; // Good luck allocating 2^30 elements
}
elements = new Object[initialCapacity];
}
@@ -136,24 +136,6 @@ public class ArrayDeque extends Abstr
}
/**
- * Copies the elements from our element array into the specified array,
- * in order (from first to last element in the deque). It is assumed
- * that the array is large enough to hold all elements in the deque.
- *
- * @return its argument
- */
- private T[] copyElements(T[] a) {
- if (head < tail) {
- System.arraycopy(elements, head, a, 0, size());
- } else if (head > tail) {
- int headPortionLen = elements.length - head;
- System.arraycopy(elements, head, a, 0, headPortionLen);
- System.arraycopy(elements, 0, a, headPortionLen, tail);
- }
- return a;
- }
-
- /**
* Constructs an empty array deque with an initial capacity
* sufficient to hold 16 elements.
*/
@@ -265,25 +247,27 @@ public class ArrayDeque extends Abstr
}
public E pollFirst() {
- int h = head;
+ final Object[] elements = this.elements;
+ final int h = head;
@SuppressWarnings("unchecked")
E result = (E) elements[h];
// Element is null if deque empty
- if (result == null)
- return null;
- elements[h] = null; // Must null out slot
- head = (h + 1) & (elements.length - 1);
+ if (result != null) {
+ elements[h] = null; // Must null out slot
+ head = (h + 1) & (elements.length - 1);
+ }
return result;
}
public E pollLast() {
- int t = (tail - 1) & (elements.length - 1);
+ final Object[] elements = this.elements;
+ final int t = (tail - 1) & (elements.length - 1);
@SuppressWarnings("unchecked")
E result = (E) elements[t];
- if (result == null)
- return null;
- elements[t] = null;
- tail = t;
+ if (result != null) {
+ elements[t] = null;
+ tail = t;
+ }
return result;
}
@@ -333,17 +317,15 @@ public class ArrayDeque extends Abstr
* @return {@code true} if the deque contained the specified element
*/
public boolean removeFirstOccurrence(Object o) {
- if (o == null)
- return false;
- int mask = elements.length - 1;
- int i = head;
- Object x;
- while ( (x = elements[i]) != null) {
- if (o.equals(x)) {
- delete(i);
- return true;
+ if (o != null) {
+ int mask = elements.length - 1;
+ int i = head;
+ for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
+ if (o.equals(x)) {
+ delete(i);
+ return true;
+ }
}
- i = (i + 1) & mask;
}
return false;
}
@@ -361,17 +343,15 @@ public class ArrayDeque extends Abstr
* @return {@code true} if the deque contained the specified element
*/
public boolean removeLastOccurrence(Object o) {
- if (o == null)
- return false;
- int mask = elements.length - 1;
- int i = (tail - 1) & mask;
- Object x;
- while ( (x = elements[i]) != null) {
- if (o.equals(x)) {
- delete(i);
- return true;
+ if (o != null) {
+ int mask = elements.length - 1;
+ int i = (tail - 1) & mask;
+ for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
+ if (o.equals(x)) {
+ delete(i);
+ return true;
+ }
}
- i = (i - 1) & mask;
}
return false;
}
@@ -508,7 +488,7 @@ public class ArrayDeque extends Abstr
*
* @return true if elements moved backwards
*/
- private boolean delete(int i) {
+ boolean delete(int i) {
checkInvariants();
final Object[] elements = this.elements;
final int mask = elements.length - 1;
@@ -628,14 +608,28 @@ public class ArrayDeque extends Abstr
}
lastRet = -1;
}
+
+ public void forEachRemaining(Consumer super E> action) {
+ Objects.requireNonNull(action);
+ Object[] a = elements;
+ int m = a.length - 1, f = fence, i = cursor;
+ cursor = f;
+ while (i != f) {
+ @SuppressWarnings("unchecked") E e = (E)a[i];
+ i = (i + 1) & m;
+ if (e == null)
+ throw new ConcurrentModificationException();
+ action.accept(e);
+ }
+ }
}
+ /**
+ * This class is nearly a mirror-image of DeqIterator, using tail
+ * instead of head for initial cursor, and head instead of tail
+ * for fence.
+ */
private class DescendingIterator implements Iterator {
- /*
- * This class is nearly a mirror-image of DeqIterator, using
- * tail instead of head for initial cursor, and head instead of
- * tail for fence.
- */
private int cursor = tail;
private int fence = head;
private int lastRet = -1;
@@ -676,15 +670,13 @@ public class ArrayDeque extends Abstr
* @return {@code true} if this deque contains the specified element
*/
public boolean contains(Object o) {
- if (o == null)
- return false;
- int mask = elements.length - 1;
- int i = head;
- Object x;
- while ( (x = elements[i]) != null) {
- if (o.equals(x))
- return true;
- i = (i + 1) & mask;
+ if (o != null) {
+ int mask = elements.length - 1;
+ int i = head;
+ for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
+ if (o.equals(x))
+ return true;
+ }
}
return false;
}
@@ -738,7 +730,14 @@ public class ArrayDeque extends Abstr
* @return an array containing all of the elements in this deque
*/
public Object[] toArray() {
- return copyElements(new Object[size()]);
+ final int head = this.head;
+ final int tail = this.tail;
+ boolean wrap = (tail < head);
+ int end = wrap ? tail + elements.length : tail;
+ Object[] a = Arrays.copyOfRange(elements, head, end);
+ if (wrap)
+ System.arraycopy(elements, 0, a, elements.length - head, tail);
+ return a;
}
/**
@@ -763,7 +762,7 @@ public class ArrayDeque extends Abstr
* The following code can be used to dump the deque into a newly
* allocated array of {@code String}:
*
- * {@code String[] y = x.toArray(new String[0]);}
+ * {@code String[] y = x.toArray(new String[0]);}
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
@@ -779,13 +778,22 @@ public class ArrayDeque extends Abstr
*/
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
- int size = size();
- if (a.length < size)
- a = (T[])java.lang.reflect.Array.newInstance(
- a.getClass().getComponentType(), size);
- copyElements(a);
- if (a.length > size)
- a[size] = null;
+ final int head = this.head;
+ final int tail = this.tail;
+ boolean wrap = (tail < head);
+ int size = (tail - head) + (wrap ? elements.length : 0);
+ int firstLeg = size - (wrap ? tail : 0);
+ int len = a.length;
+ if (size > len) {
+ a = (T[]) Arrays.copyOfRange(elements, head, head + size,
+ a.getClass());
+ } else {
+ System.arraycopy(elements, head, a, 0, firstLeg);
+ if (size < len)
+ a[size] = null;
+ }
+ if (wrap)
+ System.arraycopy(elements, 0, a, firstLeg, tail);
return a;
}
@@ -812,6 +820,8 @@ public class ArrayDeque extends Abstr
/**
* Saves this deque to a stream (that is, serializes it).
*
+ * @param s the stream
+ * @throws java.io.IOException if an I/O error occurs
* @serialData The current size ({@code int}) of the deque,
* followed by all of its elements (each an object reference) in
* first-to-last order.
@@ -831,6 +841,10 @@ public class ArrayDeque extends Abstr
/**
* Reconstitutes this deque from a stream (that is, deserializes it).
+ * @param s the stream
+ * @throws ClassNotFoundException if the class of a serialized object
+ * could not be found
+ * @throws java.io.IOException if an I/O error occurs
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
@@ -847,31 +861,46 @@ public class ArrayDeque extends Abstr
elements[i] = s.readObject();
}
- public Stream stream() {
- int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
- return Streams.stream
- (() -> new DeqSpliterator(this, head, tail), flags);
- }
- public Stream parallelStream() {
- int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
- return Streams.parallelStream
- (() -> new DeqSpliterator(this, head, tail), flags);
+ /**
+ * Creates a late-binding
+ * and fail-fast {@link Spliterator} over the elements in this
+ * deque.
+ *
+ * The {@code Spliterator} reports {@link Spliterator#SIZED},
+ * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
+ * {@link Spliterator#NONNULL}. Overriding implementations should document
+ * the reporting of additional characteristic values.
+ *
+ * @return a {@code Spliterator} over the elements in this deque
+ * @since 1.8
+ */
+ public Spliterator spliterator() {
+ return new DeqSpliterator<>(this, -1, -1);
}
-
static final class DeqSpliterator implements Spliterator {
private final ArrayDeque deq;
- private final int fence; // initially tail
- private int index; // current index, modified on traverse/split
+ private int fence; // -1 until first use
+ private int index; // current index, modified on traverse/split
- /** Create new spliterator covering the given array and range */
+ /** Creates new spliterator covering the given array and range. */
DeqSpliterator(ArrayDeque deq, int origin, int fence) {
- this.deq = deq; this.index = origin; this.fence = fence;
+ this.deq = deq;
+ this.index = origin;
+ this.fence = fence;
+ }
+
+ private int getFence() { // force initialization
+ int t;
+ if ((t = fence) < 0) {
+ t = fence = deq.tail;
+ index = deq.head;
+ }
+ return t;
}
public DeqSpliterator trySplit() {
- int n = deq.elements.length;
- int h = index, t = fence;
+ int t = getFence(), h = index, n = deq.elements.length;
if (h != t && ((h + 1) & (n - 1)) != t) {
if (h > t)
t += n;
@@ -881,46 +910,49 @@ public class ArrayDeque extends Abstr
return null;
}
- public void forEach(Consumer super E> block) {
- if (block == null)
+ public void forEachRemaining(Consumer super E> consumer) {
+ if (consumer == null)
throw new NullPointerException();
Object[] a = deq.elements;
- int m = a.length - 1, f = fence, i = index;
+ int m = a.length - 1, f = getFence(), i = index;
index = f;
while (i != f) {
@SuppressWarnings("unchecked") E e = (E)a[i];
i = (i + 1) & m;
if (e == null)
throw new ConcurrentModificationException();
- block.accept(e);
+ consumer.accept(e);
}
}
- public boolean tryAdvance(Consumer super E> block) {
- if (block == null)
+ public boolean tryAdvance(Consumer super E> consumer) {
+ if (consumer == null)
throw new NullPointerException();
Object[] a = deq.elements;
- int m = a.length - 1, i = index;
- if (i != fence) {
+ int m = a.length - 1, f = getFence(), i = index;
+ if (i != f) {
@SuppressWarnings("unchecked") E e = (E)a[i];
index = (i + 1) & m;
if (e == null)
throw new ConcurrentModificationException();
- block.accept(e);
+ consumer.accept(e);
return true;
}
return false;
}
- // Other spliterator methods
public long estimateSize() {
- int n = fence - index;
+ int n = getFence() - index;
if (n < 0)
n += deq.elements.length;
- return (long)n;
+ return (long) n;
+ }
+
+ @Override
+ public int characteristics() {
+ return Spliterator.ORDERED | Spliterator.SIZED |
+ Spliterator.NONNULL | Spliterator.SUBSIZED;
}
- public boolean hasExactSize() { return true; }
- public boolean hasExactSplits() { return true; }
}
}