diff --git a/src/share/classes/java/util/ArrayDeque.java b/src/share/classes/java/util/ArrayDeque.java
index 476b223329856ae31ea3f9e8e2e84f2419b45c6b..0e20ffc52ef69f6206642196d9dc9abec53e5822 100644
--- a/src/share/classes/java/util/ArrayDeque.java
+++ b/src/share/classes/java/util/ArrayDeque.java
@@ -33,7 +33,9 @@
*/
package java.util;
-import java.io.*;
+
+import java.io.Serializable;
+import java.util.function.Consumer;
/**
* Resizable-array implementation of the {@link Deque} interface. Array
@@ -44,16 +46,16 @@ import java.io.*;
* {@link Stack} when used as a stack, and faster than {@link LinkedList}
* when used as a queue.
*
- *
Most ArrayDeque operations run in amortized constant time.
+ *
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.
*
- *
The iterators returned by this class's iterator method are
+ *
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 remove
+ * 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
@@ -63,7 +65,7 @@ import java.io.*;
*
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.
@@ -93,20 +95,20 @@ public class ArrayDeque extends AbstractCollection
* other. We also guarantee that all array cells not holding
* deque elements are always null.
*/
- private transient E[] elements;
+ transient Object[] elements; // non-private to simplify nested class access
/**
* The index of the element at the head of the deque (which is the
* element that would be removed by remove() or pop()); or an
* arbitrary number equal to tail if the deque is empty.
*/
- private transient int head;
+ transient int head;
/**
* The index at which the next element would be added to the tail
* of the deque (via addLast(E), add(E), or push(E)).
*/
- private transient int tail;
+ transient int tail;
/**
* The minimum capacity that we'll use for a newly created deque.
@@ -117,11 +119,10 @@ public class ArrayDeque extends AbstractCollection
// ****** Array allocation and resizing utilities ******
/**
- * Allocate empty array to hold the given number of elements.
+ * Allocates empty array to hold the given number of elements.
*
* @param numElements the number of elements to hold
*/
- @SuppressWarnings("unchecked")
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
@@ -138,11 +139,11 @@ public class ArrayDeque extends AbstractCollection
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
- elements = (E[]) new Object[initialCapacity];
+ elements = new Object[initialCapacity];
}
/**
- * Double the capacity of this deque. Call only when full, i.e.,
+ * Doubles the capacity of this deque. Call only when full, i.e.,
* when head and tail have wrapped around to become equal.
*/
private void doubleCapacity() {
@@ -153,8 +154,7 @@ public class ArrayDeque extends AbstractCollection
int newCapacity = n << 1;
if (newCapacity < 0)
throw new IllegalStateException("Sorry, deque too big");
- @SuppressWarnings("unchecked")
- E[] a = (E[]) new Object[newCapacity];
+ Object[] a = new Object[newCapacity];
System.arraycopy(elements, p, a, 0, r);
System.arraycopy(elements, 0, a, r, p);
elements = a;
@@ -184,9 +184,8 @@ public class ArrayDeque extends AbstractCollection
* Constructs an empty array deque with an initial capacity
* sufficient to hold 16 elements.
*/
- @SuppressWarnings("unchecked")
public ArrayDeque() {
- elements = (E[]) new Object[16];
+ elements = new Object[16];
}
/**
@@ -252,7 +251,7 @@ public class ArrayDeque extends AbstractCollection
* Inserts the specified element at the front of this deque.
*
* @param e the element to add
- * @return true (as specified by {@link Deque#offerFirst})
+ * @return {@code true} (as specified by {@link Deque#offerFirst})
* @throws NullPointerException if the specified element is null
*/
public boolean offerFirst(E e) {
@@ -264,7 +263,7 @@ public class ArrayDeque extends AbstractCollection
* Inserts the specified element at the end of this deque.
*
* @param e the element to add
- * @return true (as specified by {@link Deque#offerLast})
+ * @return {@code true} (as specified by {@link Deque#offerLast})
* @throws NullPointerException if the specified element is null
*/
public boolean offerLast(E e) {
@@ -294,7 +293,9 @@ public class ArrayDeque extends AbstractCollection
public E pollFirst() {
int h = head;
- E result = elements[h]; // Element is null if deque empty
+ @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
@@ -304,7 +305,8 @@ public class ArrayDeque extends AbstractCollection
public E pollLast() {
int t = (tail - 1) & (elements.length - 1);
- E result = elements[t];
+ @SuppressWarnings("unchecked")
+ E result = (E) elements[t];
if (result == null)
return null;
elements[t] = null;
@@ -316,48 +318,53 @@ public class ArrayDeque extends AbstractCollection
* @throws NoSuchElementException {@inheritDoc}
*/
public E getFirst() {
- E x = elements[head];
- if (x == null)
+ @SuppressWarnings("unchecked")
+ E result = (E) elements[head];
+ if (result == null)
throw new NoSuchElementException();
- return x;
+ return result;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getLast() {
- E x = elements[(tail - 1) & (elements.length - 1)];
- if (x == null)
+ @SuppressWarnings("unchecked")
+ E result = (E) elements[(tail - 1) & (elements.length - 1)];
+ if (result == null)
throw new NoSuchElementException();
- return x;
+ return result;
}
+ @SuppressWarnings("unchecked")
public E peekFirst() {
- return elements[head]; // elements[head] is null if deque empty
+ // elements[head] is null if deque empty
+ return (E) elements[head];
}
+ @SuppressWarnings("unchecked")
public E peekLast() {
- return elements[(tail - 1) & (elements.length - 1)];
+ return (E) elements[(tail - 1) & (elements.length - 1)];
}
/**
* Removes the first occurrence of the specified element in this
* deque (when traversing the deque from head to tail).
* If the deque does not contain the element, it is unchanged.
- * More formally, removes the first element e such that
- * o.equals(e) (if such an element exists).
- * Returns true if this deque contained the specified element
+ * More formally, removes the first element {@code e} such that
+ * {@code o.equals(e)} (if such an element exists).
+ * Returns {@code true} if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
- * @return true if the deque contained the specified element
+ * @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;
- E x;
+ Object x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
@@ -372,20 +379,20 @@ public class ArrayDeque extends AbstractCollection
* Removes the last occurrence of the specified element in this
* deque (when traversing the deque from head to tail).
* If the deque does not contain the element, it is unchanged.
- * More formally, removes the last element e such that
- * o.equals(e) (if such an element exists).
- * Returns true if this deque contained the specified element
+ * More formally, removes the last element {@code e} such that
+ * {@code o.equals(e)} (if such an element exists).
+ * Returns {@code true} if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
- * @return true if the deque contained the specified element
+ * @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;
- E x;
+ Object x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
@@ -404,7 +411,7 @@ public class ArrayDeque extends AbstractCollection
* This method is equivalent to {@link #addLast}.
*
* @param e the element to add
- * @return true (as specified by {@link Collection#add})
+ * @return {@code true} (as specified by {@link Collection#add})
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
@@ -418,7 +425,7 @@ public class ArrayDeque extends AbstractCollection
* This method is equivalent to {@link #offerLast}.
*
* @param e the element to add
- * @return true (as specified by {@link Queue#offer})
+ * @return {@code true} (as specified by {@link Queue#offer})
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
@@ -443,12 +450,12 @@ public class ArrayDeque extends AbstractCollection
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque), or returns
- * null if this deque is empty.
+ * {@code null} if this deque is empty.
*
* This method is equivalent to {@link #pollFirst}.
*
* @return the head of the queue represented by this deque, or
- * null if this deque is empty
+ * {@code null} if this deque is empty
*/
public E poll() {
return pollFirst();
@@ -470,12 +477,12 @@ public class ArrayDeque extends AbstractCollection
/**
* Retrieves, but does not remove, the head of the queue represented by
- * this deque, or returns null if this deque is empty.
+ * this deque, or returns {@code null} if this deque is empty.
*
* This method is equivalent to {@link #peekFirst}.
*
* @return the head of the queue represented by this deque, or
- * null if this deque is empty
+ * {@code null} if this deque is empty
*/
public E peek() {
return peekFirst();
@@ -530,7 +537,7 @@ public class ArrayDeque extends AbstractCollection
*/
private boolean delete(int i) {
checkInvariants();
- final E[] elements = this.elements;
+ final Object[] elements = this.elements;
final int mask = elements.length - 1;
final int h = head;
final int t = tail;
@@ -579,9 +586,9 @@ public class ArrayDeque extends AbstractCollection
}
/**
- * Returns true if this deque contains no elements.
+ * Returns {@code true} if this deque contains no elements.
*
- * @return true if this deque contains no elements
+ * @return {@code true} if this deque contains no elements
*/
public boolean isEmpty() {
return head == tail;
@@ -628,7 +635,8 @@ public class ArrayDeque extends AbstractCollection
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
- E result = elements[cursor];
+ @SuppressWarnings("unchecked")
+ E result = (E) elements[cursor];
// This check doesn't catch all possible comodifications,
// but does catch the ones that corrupt traversal
if (tail != fence || result == null)
@@ -647,6 +655,20 @@ public class ArrayDeque extends AbstractCollection
}
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);
+ }
+ }
}
private class DescendingIterator implements Iterator {
@@ -667,7 +689,8 @@ public class ArrayDeque extends AbstractCollection
if (cursor == fence)
throw new NoSuchElementException();
cursor = (cursor - 1) & (elements.length - 1);
- E result = elements[cursor];
+ @SuppressWarnings("unchecked")
+ E result = (E) elements[cursor];
if (head != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
@@ -686,19 +709,19 @@ public class ArrayDeque extends AbstractCollection
}
/**
- * Returns true if this deque contains the specified element.
- * More formally, returns true if and only if this deque contains
- * at least one element e such that o.equals(e).
+ * Returns {@code true} if this deque contains the specified element.
+ * More formally, returns {@code true} if and only if this deque contains
+ * at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this deque
- * @return true if this deque contains the specified element
+ * @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;
- E x;
+ Object x;
while ( (x = elements[i]) != null) {
if (o.equals(x))
return true;
@@ -710,15 +733,15 @@ public class ArrayDeque extends AbstractCollection
/**
* Removes a single instance of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
- * More formally, removes the first element e such that
- * o.equals(e) (if such an element exists).
- * Returns true if this deque contained the specified element
+ * More formally, removes the first element {@code e} such that
+ * {@code o.equals(e)} (if such an element exists).
+ * Returns {@code true} if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
- * This method is equivalent to {@link #removeFirstOccurrence}.
+ *
This method is equivalent to {@link #removeFirstOccurrence(Object)}.
*
* @param o element to be removed from this deque, if present
- * @return true if this deque contained the specified element
+ * @return {@code true} if this deque contained the specified element
*/
public boolean remove(Object o) {
return removeFirstOccurrence(o);
@@ -770,22 +793,21 @@ public class ArrayDeque extends AbstractCollection
* If this deque fits in the specified array with room to spare
* (i.e., the array has more elements than this deque), the element in
* the array immediately following the end of the deque is set to
- * null.
+ * {@code null}.
*
*
Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* 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 deque known to contain only strings.
+ *
Suppose {@code x} is a deque known to contain only strings.
* The following code can be used to dump the deque into a newly
- * allocated array of String:
+ * allocated array of {@code String}:
*
- *
- * String[] y = x.toArray(new String[0]);
+ * {@code 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 deque are to
* be stored, if it is big enough; otherwise, a new array of the
@@ -818,28 +840,25 @@ public class ArrayDeque extends AbstractCollection
public ArrayDeque clone() {
try {
@SuppressWarnings("unchecked")
- ArrayDeque result = (ArrayDeque) super.clone();
+ ArrayDeque result = (ArrayDeque) super.clone();
result.elements = Arrays.copyOf(elements, elements.length);
return result;
-
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
- /**
- * Appease the serialization gods.
- */
private static final long serialVersionUID = 2340985798034038923L;
/**
- * Serialize this deque.
+ * Saves this deque to a stream (that is, serializes it).
*
- * @serialData The current size (int) of the deque,
+ * @serialData The current size ({@code int}) of the deque,
* followed by all of its elements (each an object reference) in
* first-to-last order.
*/
- private void writeObject(ObjectOutputStream s) throws IOException {
+ private void writeObject(java.io.ObjectOutputStream s)
+ throws java.io.IOException {
s.defaultWriteObject();
// Write out size
@@ -852,11 +871,10 @@ public class ArrayDeque extends AbstractCollection
}
/**
- * Deserialize this deque.
+ * Reconstitutes this deque from a stream (that is, deserializes it).
*/
- @SuppressWarnings("unchecked")
- private void readObject(ObjectInputStream s)
- throws IOException, ClassNotFoundException {
+ private void readObject(java.io.ObjectInputStream s)
+ throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in size and allocate array
@@ -867,6 +885,88 @@ public class ArrayDeque extends AbstractCollection
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
- elements[i] = (E)s.readObject();
+ elements[i] = s.readObject();
}
+
+ public Spliterator spliterator() {
+ return new DeqSpliterator(this, -1, -1);
+ }
+
+ static final class DeqSpliterator implements Spliterator {
+ private final ArrayDeque deq;
+ private int fence; // -1 until first use
+ private int index; // current index, modified on traverse/split
+
+ /** 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;
+ }
+
+ private int getFence() { // force initialization
+ int t;
+ if ((t = fence) < 0) {
+ t = fence = deq.tail;
+ index = deq.head;
+ }
+ return t;
+ }
+
+ public DeqSpliterator trySplit() {
+ int t = getFence(), h = index, n = deq.elements.length;
+ if (h != t && ((h + 1) & (n - 1)) != t) {
+ if (h > t)
+ t += n;
+ int m = ((h + t) >>> 1) & (n - 1);
+ return new DeqSpliterator<>(deq, h, index = m);
+ }
+ return null;
+ }
+
+ public void forEachRemaining(Consumer super E> consumer) {
+ if (consumer == null)
+ throw new NullPointerException();
+ Object[] a = deq.elements;
+ 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();
+ consumer.accept(e);
+ }
+ }
+
+ public boolean tryAdvance(Consumer super E> consumer) {
+ if (consumer == null)
+ throw new NullPointerException();
+ Object[] a = deq.elements;
+ int m = a.length - 1, f = getFence(), i = index;
+ if (i != fence) {
+ @SuppressWarnings("unchecked") E e = (E)a[i];
+ index = (i + 1) & m;
+ if (e == null)
+ throw new ConcurrentModificationException();
+ consumer.accept(e);
+ return true;
+ }
+ return false;
+ }
+
+ public long estimateSize() {
+ int n = getFence() - index;
+ if (n < 0)
+ n += deq.elements.length;
+ return (long) n;
+ }
+
+ @Override
+ public int characteristics() {
+ return Spliterator.ORDERED | Spliterator.SIZED |
+ Spliterator.NONNULL | Spliterator.SUBSIZED;
+ }
+ }
+
}
diff --git a/src/share/classes/java/util/ArrayList.java b/src/share/classes/java/util/ArrayList.java
index c6be686e7dd7b70cf1a24bbd295e6db85ec546fd..dde4332e78feb3edbe2e95c04956cc0d38858af6 100644
--- a/src/share/classes/java/util/ArrayList.java
+++ b/src/share/classes/java/util/ArrayList.java
@@ -29,6 +29,10 @@ import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
+import java.util.function.Consumer;
+import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
+
/**
* Resizable-array implementation of the List interface. Implements
* all optional list operations, and permits all elements, including
@@ -124,7 +128,7 @@ public class ArrayList extends AbstractList
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
*/
- private transient Object[] elementData;
+ transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
@@ -857,6 +861,27 @@ public class ArrayList extends AbstractList
}
}
+ @Override
+ @SuppressWarnings("unchecked")
+ public void forEachRemaining(Consumer super E> consumer) {
+ Objects.requireNonNull(consumer);
+ final int size = ArrayList.this.size;
+ int i = cursor;
+ if (i >= size) {
+ return;
+ }
+ final Object[] elementData = ArrayList.this.elementData;
+ if (i >= elementData.length) {
+ throw new ConcurrentModificationException();
+ }
+ while (i != size && modCount == expectedModCount) {
+ consumer.accept((E) elementData[i++]);
+ }
+ // update once at end of iteration to reduce heap write traffic
+ lastRet = cursor = i;
+ checkForComodification();
+ }
+
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
@@ -1092,6 +1117,26 @@ public class ArrayList extends AbstractList
return (E) elementData[offset + (lastRet = i)];
}
+ @SuppressWarnings("unchecked")
+ public void forEachRemaining(Consumer super E> consumer) {
+ Objects.requireNonNull(consumer);
+ final int size = SubList.this.size;
+ int i = cursor;
+ if (i >= size) {
+ return;
+ }
+ final Object[] elementData = ArrayList.this.elementData;
+ if (offset + i >= elementData.length) {
+ throw new ConcurrentModificationException();
+ }
+ while (i != size && modCount == expectedModCount) {
+ consumer.accept((E) elementData[offset + (i++)]);
+ }
+ // update once at end of iteration to reduce heap write traffic
+ lastRet = cursor = i;
+ checkForComodification();
+ }
+
public int nextIndex() {
return cursor;
}
@@ -1171,6 +1216,12 @@ public class ArrayList extends AbstractList
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
+
+ public Spliterator spliterator() {
+ checkForComodification();
+ return new ArrayListSpliterator(ArrayList.this, offset,
+ offset + this.size, this.modCount);
+ }
}
@Override
@@ -1188,6 +1239,128 @@ public class ArrayList extends AbstractList
}
}
+ public Spliterator spliterator() {
+ return new ArrayListSpliterator<>(this, 0, -1, 0);
+ }
+
+ /** Index-based split-by-two, lazily initialized Spliterator */
+ static final class ArrayListSpliterator implements Spliterator {
+
+ /*
+ * If ArrayLists were immutable, or structurally immutable (no
+ * adds, removes, etc), we could implement their spliterators
+ * with Arrays.spliterator. Instead we detect as much
+ * interference during traversal as practical without
+ * sacrificing much performance. We rely primarily on
+ * modCounts. These are not guaranteed to detect concurrency
+ * violations, and are sometimes overly conservative about
+ * within-thread interference, but detect enough problems to
+ * be worthwhile in practice. To carry this out, we (1) lazily
+ * initialize fence and expectedModCount until the latest
+ * point that we need to commit to the state we are checking
+ * against; thus improving precision. (This doesn't apply to
+ * SubLists, that create spliterators with current non-lazy
+ * values). (2) We perform only a single
+ * ConcurrentModificationException check at the end of forEach
+ * (the most performance-sensitive method). When using forEach
+ * (as opposed to iterators), we can normally only detect
+ * interference after actions, not before. Further
+ * CME-triggering checks apply to all other possible
+ * violations of assumptions for example null or too-small
+ * elementData array given its size(), that could only have
+ * occurred due to interference. This allows the inner loop
+ * of forEach to run without any further checks, and
+ * simplifies lambda-resolution. While this does entail a
+ * number of checks, note that in the common case of
+ * list.stream().forEach(a), no checks or other computation
+ * occur anywhere other than inside forEach itself. The other
+ * less-often-used methods cannot take advantage of most of
+ * these streamlinings.
+ */
+
+ private final ArrayList list;
+ private int index; // current index, modified on advance/split
+ private int fence; // -1 until used; then one past last index
+ private int expectedModCount; // initialized when fence set
+
+ /** Create new spliterator covering the given range */
+ ArrayListSpliterator(ArrayList list, int origin, int fence,
+ int expectedModCount) {
+ this.list = list; // OK if null unless traversed
+ this.index = origin;
+ this.fence = fence;
+ this.expectedModCount = expectedModCount;
+ }
+
+ private int getFence() { // initialize fence to size on first use
+ int hi; // (a specialized variant appears in method forEach)
+ ArrayList lst;
+ if ((hi = fence) < 0) {
+ if ((lst = list) == null)
+ hi = fence = 0;
+ else {
+ expectedModCount = lst.modCount;
+ hi = fence = lst.size;
+ }
+ }
+ return hi;
+ }
+
+ public ArrayListSpliterator trySplit() {
+ int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
+ return (lo >= mid) ? null : // divide range in half unless too small
+ new ArrayListSpliterator(list, lo, index = mid,
+ expectedModCount);
+ }
+
+ public boolean tryAdvance(Consumer super E> action) {
+ if (action == null)
+ throw new NullPointerException();
+ int hi = getFence(), i = index;
+ if (i < hi) {
+ index = i + 1;
+ @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
+ action.accept(e);
+ if (list.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ return false;
+ }
+
+ public void forEachRemaining(Consumer super E> action) {
+ int i, hi, mc; // hoist accesses and checks from loop
+ ArrayList lst; Object[] a;
+ if (action == null)
+ throw new NullPointerException();
+ if ((lst = list) != null && (a = lst.elementData) != null) {
+ if ((hi = fence) < 0) {
+ mc = lst.modCount;
+ hi = lst.size;
+ }
+ else
+ mc = expectedModCount;
+ if ((i = index) >= 0 && (index = hi) <= a.length) {
+ for (; i < hi; ++i) {
+ @SuppressWarnings("unchecked") E e = (E) a[i];
+ action.accept(e);
+ }
+ if (lst.modCount == mc)
+ return;
+ }
+ }
+ throw new ConcurrentModificationException();
+ }
+
+ public long estimateSize() {
+ return (long) (getFence() - index);
+ }
+
+ public int characteristics() {
+ return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
+ }
+ }
+
@Override
public boolean removeIf(Predicate super E> filter) {
Objects.requireNonNull(filter);
diff --git a/src/share/classes/java/util/Collections.java b/src/share/classes/java/util/Collections.java
index 2cc690d8e582af65fbe9b883d5dfc85e16e7c20c..30d589cdc7d57ed479e16b59ffab96466849db54 100644
--- a/src/share/classes/java/util/Collections.java
+++ b/src/share/classes/java/util/Collections.java
@@ -1088,6 +1088,11 @@ public class Collections {
public void remove() {
throw new UnsupportedOperationException();
}
+ @Override
+ public void forEachRemaining(Consumer super E> action) {
+ // Use backing collection version
+ i.forEachRemaining(action);
+ }
};
}
@@ -1114,6 +1119,7 @@ public class Collections {
throw new UnsupportedOperationException();
}
+ // Override default methods in Collection
@Override
public void forEach(Consumer super E> action) {
c.forEach(action);
@@ -1122,6 +1128,11 @@ public class Collections {
public boolean removeIf(Predicate super E> filter) {
throw new UnsupportedOperationException();
}
+ @Override
+ public Spliterator spliterator() {
+ return (Spliterator)c.spliterator();
+ }
+
}
/**
@@ -1285,6 +1296,11 @@ public class Collections {
public void add(E e) {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public void forEachRemaining(Consumer super E> action) {
+ i.forEachRemaining(action);
+ }
};
}
@@ -1664,7 +1680,8 @@ public class Collections {
* through the returned collection.
*
* It is imperative that the user manually synchronize on the returned
- * collection when iterating over it:
+ * collection when traversing it via {@link Iterator} or
+ * {@link Spliterator}:
*
* Collection c = Collections.synchronizedCollection(myCollection);
* ...
@@ -1761,18 +1778,22 @@ public class Collections {
public String toString() {
synchronized (mutex) {return c.toString();}
}
- private void writeObject(ObjectOutputStream s) throws IOException {
- synchronized (mutex) {s.defaultWriteObject();}
- }
-
+ // Override default methods in Collection
@Override
- public void forEach(Consumer super E> action) {
- synchronized (mutex) {c.forEach(action);}
+ public void forEach(Consumer super E> consumer) {
+ synchronized (mutex) {c.forEach(consumer);}
}
@Override
public boolean removeIf(Predicate super E> filter) {
synchronized (mutex) {return c.removeIf(filter);}
}
+ @Override
+ public Spliterator spliterator() {
+ return c.spliterator(); // Must be manually synched by user!
+ }
+ private void writeObject(ObjectOutputStream s) throws IOException {
+ synchronized (mutex) {s.defaultWriteObject();}
+ }
}
/**
@@ -2533,14 +2554,15 @@ public class Collections {
return c.addAll(checkedCopyOf(coll));
}
+ // Override default methods in Collection
@Override
- public void forEach(Consumer super E> action) {
- c.forEach(action);
- }
+ public void forEach(Consumer super E> action) {c.forEach(action);}
@Override
public boolean removeIf(Predicate super E> filter) {
return c.removeIf(filter);
}
+ @Override
+ public Spliterator spliterator() {return c.spliterator();}
}
/**
@@ -2796,6 +2818,11 @@ public class Collections {
typeCheck(e);
i.add(e);
}
+
+ @Override
+ public void forEachRemaining(Consumer super E> action) {
+ i.forEachRemaining(action);
+ }
};
}
@@ -3334,6 +3361,10 @@ public class Collections {
public boolean hasNext() { return false; }
public E next() { throw new NoSuchElementException(); }
public void remove() { throw new IllegalStateException(); }
+ @Override
+ public void forEachRemaining(Consumer super E> action) {
+ Objects.requireNonNull(action);
+ }
}
/**
@@ -3474,6 +3505,7 @@ public class Collections {
return a;
}
+ // Override default methods in Collection
@Override
public void forEach(Consumer super E> action) {
Objects.requireNonNull(action);
@@ -3483,6 +3515,8 @@ public class Collections {
Objects.requireNonNull(filter);
return false;
}
+ @Override
+ public Spliterator spliterator() { return Spliterators.emptySpliterator(); }
// Preserves singleton property
private Object readResolve() {
@@ -3592,15 +3626,20 @@ public class Collections {
throw new NoSuchElementException();
}
+ // Override default methods in Collection
@Override
public void forEach(Consumer super E> action) {
Objects.requireNonNull(action);
}
+
@Override
public boolean removeIf(Predicate super E> filter) {
Objects.requireNonNull(filter);
return false;
}
+
+ @Override
+ public Spliterator spliterator() { return Spliterators.emptySpliterator(); }
}
/**
@@ -3670,10 +3709,6 @@ public class Collections {
public int hashCode() { return 1; }
- @Override
- public void forEach(Consumer super E> action) {
- Objects.requireNonNull(action);
- }
@Override
public boolean removeIf(Predicate super E> filter) {
Objects.requireNonNull(filter);
@@ -3688,6 +3723,15 @@ public class Collections {
Objects.requireNonNull(c);
}
+ // Override default methods in Collection
+ @Override
+ public void forEach(Consumer super E> action) {
+ Objects.requireNonNull(action);
+ }
+
+ @Override
+ public Spliterator spliterator() { return Spliterators.emptySpliterator(); }
+
// Preserves singleton property
private Object readResolve() {
return EMPTY_LIST;
@@ -3843,6 +3887,60 @@ public class Collections {
public void remove() {
throw new UnsupportedOperationException();
}
+ @Override
+ public void forEachRemaining(Consumer super E> action) {
+ Objects.requireNonNull(action);
+ if (hasNext) {
+ action.accept(e);
+ hasNext = false;
+ }
+ }
+ };
+ }
+
+ /**
+ * Creates a {@code Spliterator} with only the specified element
+ *
+ * @param Type of elements
+ * @return A singleton {@code Spliterator}
+ */
+ static Spliterator singletonSpliterator(final T element) {
+ return new Spliterator() {
+ long est = 1;
+
+ @Override
+ public Spliterator trySplit() {
+ return null;
+ }
+
+ @Override
+ public boolean tryAdvance(Consumer super T> consumer) {
+ Objects.requireNonNull(consumer);
+ if (est > 0) {
+ est--;
+ consumer.accept(element);
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void forEachRemaining(Consumer super T> consumer) {
+ tryAdvance(consumer);
+ }
+
+ @Override
+ public long estimateSize() {
+ return est;
+ }
+
+ @Override
+ public int characteristics() {
+ int value = (element != null) ? Spliterator.NONNULL : 0;
+
+ return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |
+ Spliterator.DISTINCT | Spliterator.ORDERED;
+ }
};
}
@@ -3867,11 +3965,16 @@ public class Collections {
public boolean contains(Object o) {return eq(o, element);}
+ // Override default methods for Collection
@Override
public void forEach(Consumer super E> action) {
action.accept(element);
}
@Override
+ public Spliterator spliterator() {
+ return singletonSpliterator(element);
+ }
+ @Override
public boolean removeIf(Predicate super E> filter) {
throw new UnsupportedOperationException();
}
@@ -3916,6 +4019,7 @@ public class Collections {
return element;
}
+ // Override default methods for Collection
@Override
public void forEach(Consumer super E> action) {
action.accept(element);
@@ -3931,6 +4035,10 @@ public class Collections {
@Override
public void sort(Comparator super E> c) {
}
+ @Override
+ public Spliterator spliterator() {
+ return singletonSpliterator(element);
+ }
}
/**
@@ -4529,6 +4637,7 @@ public class Collections {
public boolean retainAll(Collection> c) {return s.retainAll(c);}
// addAll is the only inherited implementation
+ // Override default methods in Collection
@Override
public void forEach(Consumer super E> action) {
s.forEach(action);
@@ -4538,6 +4647,9 @@ public class Collections {
return s.removeIf(filter);
}
+ @Override
+ public Spliterator spliterator() {return s.spliterator();}
+
private static final long serialVersionUID = 2454657854757543876L;
private void readObject(java.io.ObjectInputStream stream)
@@ -4597,10 +4709,11 @@ public class Collections {
public boolean retainAll(Collection> c) {return q.retainAll(c);}
// We use inherited addAll; forwarding addAll would be wrong
+ // Override default methods in Collection
@Override
- public void forEach(Consumer super E> action) {
- q.forEach(action);
- }
+ public void forEach(Consumer super E> action) {q.forEach(action);}
+ @Override
+ public Spliterator spliterator() {return q.spliterator();}
@Override
public boolean removeIf(Predicate super E> filter) {
return q.removeIf(filter);
diff --git a/src/share/classes/java/util/HashMap.java b/src/share/classes/java/util/HashMap.java
index b40c5c92ffae182d0caa85d848829aed7c080054..5e79498da9fca72bbc50e145319c7643bb19e7e3 100644
--- a/src/share/classes/java/util/HashMap.java
+++ b/src/share/classes/java/util/HashMap.java
@@ -1230,6 +1230,14 @@ public class HashMap
public void clear() {
HashMap.this.clear();
}
+
+ public Spliterator spliterator() {
+ if (HashMap.this.getClass() == HashMap.class)
+ return new KeySpliterator(HashMap.this, 0, -1, 0, 0);
+ else
+ return Spliterators.spliterator
+ (this, Spliterator.SIZED | Spliterator.DISTINCT);
+ }
}
/**
@@ -1263,6 +1271,14 @@ public class HashMap
public void clear() {
HashMap.this.clear();
}
+
+ public Spliterator spliterator() {
+ if (HashMap.this.getClass() == HashMap.class)
+ return new ValueSpliterator(HashMap.this, 0, -1, 0, 0);
+ else
+ return Spliterators.spliterator
+ (this, Spliterator.SIZED);
+ }
}
/**
@@ -1310,6 +1326,14 @@ public class HashMap
public void clear() {
HashMap.this.clear();
}
+
+ public Spliterator> spliterator() {
+ if (HashMap.this.getClass() == HashMap.class)
+ return new EntrySpliterator(HashMap.this, 0, -1, 0, 0);
+ else
+ return Spliterators.spliterator
+ (this, Spliterator.SIZED | Spliterator.DISTINCT);
+ }
}
/**
@@ -1406,4 +1430,257 @@ public class HashMap
// These methods are used when serializing HashSets
int capacity() { return table.length; }
float loadFactor() { return loadFactor; }
+
+ /**
+ * Standin until HM overhaul; based loosely on Weak and Identity HM.
+ */
+ static class HashMapSpliterator {
+ final HashMap map;
+ HashMap.Entry current; // current node
+ int index; // current index, modified on advance/split
+ int fence; // one past last index
+ int est; // size estimate
+ int expectedModCount; // for comodification checks
+
+ HashMapSpliterator(HashMap m, int origin,
+ int fence, int est,
+ int expectedModCount) {
+ this.map = m;
+ this.index = origin;
+ this.fence = fence;
+ this.est = est;
+ this.expectedModCount = expectedModCount;
+ }
+
+ final int getFence() { // initialize fence and size on first use
+ int hi;
+ if ((hi = fence) < 0) {
+ HashMap m = map;
+ est = m.size;
+ expectedModCount = m.modCount;
+ hi = fence = m.table.length;
+ }
+ return hi;
+ }
+
+ public final long estimateSize() {
+ getFence(); // force init
+ return (long) est;
+ }
+ }
+
+ static final class KeySpliterator
+ extends HashMapSpliterator
+ implements Spliterator {
+ KeySpliterator(HashMap m, int origin, int fence, int est,
+ int expectedModCount) {
+ super(m, origin, fence, est, expectedModCount);
+ }
+
+ public KeySpliterator trySplit() {
+ int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
+ return (lo >= mid || current != null) ? null :
+ new KeySpliterator(map, lo, index = mid, est >>>= 1,
+ expectedModCount);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void forEachRemaining(Consumer super K> action) {
+ int i, hi, mc;
+ if (action == null)
+ throw new NullPointerException();
+ HashMap m = map;
+ HashMap.Entry[] tab = (HashMap.Entry[])m.table;
+ if ((hi = fence) < 0) {
+ mc = expectedModCount = m.modCount;
+ hi = fence = tab.length;
+ }
+ else
+ mc = expectedModCount;
+ if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
+ HashMap.Entry p = current;
+ do {
+ if (p == null)
+ p = tab[i++];
+ else {
+ action.accept(p.getKey());
+ p = p.next;
+ }
+ } while (p != null || i < hi);
+ if (m.modCount != mc)
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public boolean tryAdvance(Consumer super K> action) {
+ int hi;
+ if (action == null)
+ throw new NullPointerException();
+ HashMap.Entry[] tab = (HashMap.Entry[])map.table;
+ if (tab.length >= (hi = getFence()) && index >= 0) {
+ while (current != null || index < hi) {
+ if (current == null)
+ current = tab[index++];
+ else {
+ K k = current.getKey();
+ current = current.next;
+ action.accept(k);
+ if (map.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public int characteristics() {
+ return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
+ Spliterator.DISTINCT;
+ }
+ }
+
+ static final class ValueSpliterator
+ extends HashMapSpliterator
+ implements Spliterator {
+ ValueSpliterator(HashMap m, int origin, int fence, int est,
+ int expectedModCount) {
+ super(m, origin, fence, est, expectedModCount);
+ }
+
+ public ValueSpliterator trySplit() {
+ int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
+ return (lo >= mid || current != null) ? null :
+ new ValueSpliterator(map, lo, index = mid, est >>>= 1,
+ expectedModCount);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void forEachRemaining(Consumer super V> action) {
+ int i, hi, mc;
+ if (action == null)
+ throw new NullPointerException();
+ HashMap m = map;
+ HashMap.Entry[] tab = (HashMap.Entry[])m.table;
+ if ((hi = fence) < 0) {
+ mc = expectedModCount = m.modCount;
+ hi = fence = tab.length;
+ }
+ else
+ mc = expectedModCount;
+ if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
+ HashMap.Entry p = current;
+ do {
+ if (p == null)
+ p = tab[i++];
+ else {
+ action.accept(p.getValue());
+ p = p.next;
+ }
+ } while (p != null || i < hi);
+ if (m.modCount != mc)
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public boolean tryAdvance(Consumer super V> action) {
+ int hi;
+ if (action == null)
+ throw new NullPointerException();
+ HashMap.Entry[] tab = (HashMap.Entry[])map.table;
+ if (tab.length >= (hi = getFence()) && index >= 0) {
+ while (current != null || index < hi) {
+ if (current == null)
+ current = tab[index++];
+ else {
+ V v = current.getValue();
+ current = current.next;
+ action.accept(v);
+ if (map.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public int characteristics() {
+ return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
+ }
+ }
+
+ static final class EntrySpliterator
+ extends HashMapSpliterator
+ implements Spliterator> {
+ EntrySpliterator(HashMap m, int origin, int fence, int est,
+ int expectedModCount) {
+ super(m, origin, fence, est, expectedModCount);
+ }
+
+ public EntrySpliterator trySplit() {
+ int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
+ return (lo >= mid || current != null) ? null :
+ new EntrySpliterator(map, lo, index = mid, est >>>= 1,
+ expectedModCount);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void forEachRemaining(Consumer super Map.Entry> action) {
+ int i, hi, mc;
+ if (action == null)
+ throw new NullPointerException();
+ HashMap m = map;
+ HashMap.Entry[] tab = (HashMap.Entry[])m.table;
+ if ((hi = fence) < 0) {
+ mc = expectedModCount = m.modCount;
+ hi = fence = tab.length;
+ }
+ else
+ mc = expectedModCount;
+ if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
+ HashMap.Entry p = current;
+ do {
+ if (p == null)
+ p = tab[i++];
+ else {
+ action.accept(p);
+ p = p.next;
+ }
+ } while (p != null || i < hi);
+ if (m.modCount != mc)
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public boolean tryAdvance(Consumer super Map.Entry> action) {
+ int hi;
+ if (action == null)
+ throw new NullPointerException();
+ HashMap.Entry[] tab = (HashMap.Entry[])map.table;
+ if (tab.length >= (hi = getFence()) && index >= 0) {
+ while (current != null || index < hi) {
+ if (current == null)
+ current = tab[index++];
+ else {
+ HashMap.Entry e = current;
+ current = current.next;
+ action.accept(e);
+ if (map.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public int characteristics() {
+ return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
+ Spliterator.DISTINCT;
+ }
+ }
}
diff --git a/src/share/classes/java/util/HashSet.java b/src/share/classes/java/util/HashSet.java
index f7e987143fc98976cc259026d66bc297003e9a96..002b80cbe6867ff9284c7f6b29c12dea64400522 100644
--- a/src/share/classes/java/util/HashSet.java
+++ b/src/share/classes/java/util/HashSet.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -311,4 +311,8 @@ public class HashSet
map.put(e, PRESENT);
}
}
+
+ public Spliterator spliterator() {
+ return new HashMap.KeySpliterator(map, 0, -1, 0, 0);
+ }
}
diff --git a/src/share/classes/java/util/IdentityHashMap.java b/src/share/classes/java/util/IdentityHashMap.java
index 49bb9943ff60497bca2fceba6aa179c14f4c4877..eb54db623e4fc07c5d3dd26d1b847b4f99767d5a 100644
--- a/src/share/classes/java/util/IdentityHashMap.java
+++ b/src/share/classes/java/util/IdentityHashMap.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,8 +24,10 @@
*/
package java.util;
+
import java.io.*;
import java.lang.reflect.Array;
+import java.util.function.Consumer;
/**
* This class implements the Map interface with a hash table, using
@@ -162,19 +164,19 @@ public class IdentityHashMap
/**
* The table, resized as necessary. Length MUST always be a power of two.
*/
- private transient Object[] table;
+ transient Object[] table; // non-private to simplify nested class access
/**
* The number of key-value mappings contained in this identity hash map.
*
* @serial
*/
- private int size;
+ int size;
/**
* The number of modifications, to support fast-fail iterators
*/
- private transient int modCount;
+ transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
@@ -184,7 +186,7 @@ public class IdentityHashMap
/**
* Value representing null keys inside tables.
*/
- private static final Object NULL_KEY = new Object();
+ static final Object NULL_KEY = new Object();
/**
* Use NULL_KEY for key if it is null.
@@ -196,7 +198,7 @@ public class IdentityHashMap
/**
* Returns internal representation of null key back to caller as null.
*/
- private static Object unmaskNull(Object key) {
+ static final Object unmaskNull(Object key) {
return (key == NULL_KEY ? null : key);
}
@@ -1012,7 +1014,7 @@ public class IdentityHashMap
return result;
}
public Object[] toArray() {
- return toArray(new Object[size()]);
+ return toArray(new Object[0]);
}
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
@@ -1042,6 +1044,10 @@ public class IdentityHashMap
}
return a;
}
+
+ public Spliterator spliterator() {
+ return new KeySpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
+ }
}
/**
@@ -1095,7 +1101,7 @@ public class IdentityHashMap
IdentityHashMap.this.clear();
}
public Object[] toArray() {
- return toArray(new Object[size()]);
+ return toArray(new Object[0]);
}
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
@@ -1124,6 +1130,10 @@ public class IdentityHashMap
}
return a;
}
+
+ public Spliterator spliterator() {
+ return new ValueSpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
+ }
}
/**
@@ -1211,7 +1221,7 @@ public class IdentityHashMap
}
public Object[] toArray() {
- return toArray(new Object[size()]);
+ return toArray(new Object[0]);
}
@SuppressWarnings("unchecked")
@@ -1242,6 +1252,10 @@ public class IdentityHashMap
}
return a;
}
+
+ public Spliterator> spliterator() {
+ return new EntrySpliterator<>(IdentityHashMap.this, 0, -1, 0, 0);
+ }
}
@@ -1322,4 +1336,223 @@ public class IdentityHashMap
tab[i] = k;
tab[i + 1] = value;
}
+
+ /**
+ * Similar form as array-based Spliterators, but skips blank elements,
+ * and guestimates size as decreasing by half per split.
+ */
+ static class IdentityHashMapSpliterator {
+ final IdentityHashMap map;
+ int index; // current index, modified on advance/split
+ int fence; // -1 until first use; then one past last index
+ int est; // size estimate
+ int expectedModCount; // initialized when fence set
+
+ IdentityHashMapSpliterator(IdentityHashMap map, int origin,
+ int fence, int est, int expectedModCount) {
+ this.map = map;
+ this.index = origin;
+ this.fence = fence;
+ this.est = est;
+ this.expectedModCount = expectedModCount;
+ }
+
+ final int getFence() { // initialize fence and size on first use
+ int hi;
+ if ((hi = fence) < 0) {
+ est = map.size;
+ expectedModCount = map.modCount;
+ hi = fence = map.table.length;
+ }
+ return hi;
+ }
+
+ public final long estimateSize() {
+ getFence(); // force init
+ return (long) est;
+ }
+ }
+
+ static final class KeySpliterator
+ extends IdentityHashMapSpliterator
+ implements Spliterator {
+ KeySpliterator(IdentityHashMap map, int origin, int fence, int est,
+ int expectedModCount) {
+ super(map, origin, fence, est, expectedModCount);
+ }
+
+ public KeySpliterator trySplit() {
+ int hi = getFence(), lo = index, mid = ((lo + hi) >>> 1) & ~1;
+ return (lo >= mid) ? null :
+ new KeySpliterator(map, lo, index = mid, est >>>= 1,
+ expectedModCount);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void forEachRemaining(Consumer super K> action) {
+ if (action == null)
+ throw new NullPointerException();
+ int i, hi, mc; Object key;
+ IdentityHashMap m; Object[] a;
+ if ((m = map) != null && (a = m.table) != null &&
+ (i = index) >= 0 && (index = hi = getFence()) <= a.length) {
+ for (; i < hi; i += 2) {
+ if ((key = a[i]) != null)
+ action.accept((K)unmaskNull(key));
+ }
+ if (m.modCount == expectedModCount)
+ return;
+ }
+ throw new ConcurrentModificationException();
+ }
+
+ @SuppressWarnings("unchecked")
+ public boolean tryAdvance(Consumer super K> action) {
+ if (action == null)
+ throw new NullPointerException();
+ Object[] a = map.table;
+ int hi = getFence();
+ while (index < hi) {
+ Object key = a[index];
+ index += 2;
+ if (key != null) {
+ action.accept((K)unmaskNull(key));
+ if (map.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public int characteristics() {
+ return (fence < 0 || est == map.size ? SIZED : 0) | Spliterator.DISTINCT;
+ }
+ }
+
+ static final class ValueSpliterator
+ extends IdentityHashMapSpliterator
+ implements Spliterator {
+ ValueSpliterator(IdentityHashMap m, int origin, int fence, int est,
+ int expectedModCount) {
+ super(m, origin, fence, est, expectedModCount);
+ }
+
+ public ValueSpliterator trySplit() {
+ int hi = getFence(), lo = index, mid = ((lo + hi) >>> 1) & ~1;
+ return (lo >= mid) ? null :
+ new ValueSpliterator(map, lo, index = mid, est >>>= 1,
+ expectedModCount);
+ }
+
+ public void forEachRemaining(Consumer super V> action) {
+ if (action == null)
+ throw new NullPointerException();
+ int i, hi, mc;
+ IdentityHashMap m; Object[] a;
+ if ((m = map) != null && (a = m.table) != null &&
+ (i = index) >= 0 && (index = hi = getFence()) <= a.length) {
+ for (; i < hi; i += 2) {
+ if (a[i] != null) {
+ @SuppressWarnings("unchecked") V v = (V)a[i+1];
+ action.accept(v);
+ }
+ }
+ if (m.modCount == expectedModCount)
+ return;
+ }
+ throw new ConcurrentModificationException();
+ }
+
+ public boolean tryAdvance(Consumer super V> action) {
+ if (action == null)
+ throw new NullPointerException();
+ Object[] a = map.table;
+ int hi = getFence();
+ while (index < hi) {
+ Object key = a[index];
+ @SuppressWarnings("unchecked") V v = (V)a[index+1];
+ index += 2;
+ if (key != null) {
+ action.accept(v);
+ if (map.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public int characteristics() {
+ return (fence < 0 || est == map.size ? SIZED : 0);
+ }
+
+ }
+
+ static final class EntrySpliterator
+ extends IdentityHashMapSpliterator
+ implements Spliterator> {
+ EntrySpliterator(IdentityHashMap m, int origin, int fence, int est,
+ int expectedModCount) {
+ super(m, origin, fence, est, expectedModCount);
+ }
+
+ public EntrySpliterator trySplit() {
+ int hi = getFence(), lo = index, mid = ((lo + hi) >>> 1) & ~1;
+ return (lo >= mid) ? null :
+ new EntrySpliterator(map, lo, index = mid, est >>>= 1,
+ expectedModCount);
+ }
+
+ public void forEachRemaining(Consumer super Map.Entry> action) {
+ if (action == null)
+ throw new NullPointerException();
+ int i, hi, mc;
+ IdentityHashMap m; Object[] a;
+ if ((m = map) != null && (a = m.table) != null &&
+ (i = index) >= 0 && (index = hi = getFence()) <= a.length) {
+ for (; i < hi; i += 2) {
+ Object key = a[i];
+ if (key != null) {
+ @SuppressWarnings("unchecked") K k =
+ (K)unmaskNull(key);
+ @SuppressWarnings("unchecked") V v = (V)a[i+1];
+ action.accept
+ (new AbstractMap.SimpleImmutableEntry(k, v));
+
+ }
+ }
+ if (m.modCount == expectedModCount)
+ return;
+ }
+ throw new ConcurrentModificationException();
+ }
+
+ public boolean tryAdvance(Consumer super Map.Entry> action) {
+ if (action == null)
+ throw new NullPointerException();
+ Object[] a = map.table;
+ int hi = getFence();
+ while (index < hi) {
+ Object key = a[index];
+ @SuppressWarnings("unchecked") V v = (V)a[index+1];
+ index += 2;
+ if (key != null) {
+ @SuppressWarnings("unchecked") K k =
+ (K)unmaskNull(key);
+ action.accept
+ (new AbstractMap.SimpleImmutableEntry(k, v));
+ if (map.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public int characteristics() {
+ return (fence < 0 || est == map.size ? SIZED : 0) | Spliterator.DISTINCT;
+ }
+ }
+
}
diff --git a/src/share/classes/java/util/LinkedHashSet.java b/src/share/classes/java/util/LinkedHashSet.java
index 399ba80fe99bb543730b125209c0aef3d74cd736..c66015aac6f6bb3106cf770f5a3fb6a3a34cf620 100644
--- a/src/share/classes/java/util/LinkedHashSet.java
+++ b/src/share/classes/java/util/LinkedHashSet.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -168,4 +168,18 @@ public class LinkedHashSet
super(Math.max(2*c.size(), 11), .75f, true);
addAll(c);
}
+
+ /**
+ * Creates a {@code Spliterator}, over the elements in this set, that
+ * reports {@code SIZED}, {@code DISTINCT} and {@code ORDERED}.
+ * Overriding implementations are expected to document if the
+ * {@code Spliterator} reports any additional and relevant characteristic
+ * values.
+ *
+ * @return a {@code Spliterator} over the elements in this set
+ */
+ @Override
+ public Spliterator spliterator() {
+ return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
+ }
}
diff --git a/src/share/classes/java/util/LinkedList.java b/src/share/classes/java/util/LinkedList.java
index fd8f181f17f197731f4d8761c7bd160c178aa17b..5db6874e25524c3ded7775d049fc3892ec88bbae 100644
--- a/src/share/classes/java/util/LinkedList.java
+++ b/src/share/classes/java/util/LinkedList.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
package java.util;
+import java.util.function.Consumer;
+
/**
* Doubly-linked list implementation of the {@code List} and {@code Deque}
* interfaces. Implements all optional list operations, and permits all
@@ -948,6 +950,16 @@ public class LinkedList
expectedModCount++;
}
+ public void forEachRemaining(Consumer super E> action) {
+ Objects.requireNonNull(action);
+ while (modCount == expectedModCount && nextIndex < size) {
+ action.accept(next.item);
+ next = next.next;
+ nextIndex++;
+ }
+ checkForComodification();
+ }
+
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
@@ -1135,4 +1147,103 @@ public class LinkedList
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}
+
+ public Spliterator spliterator() {
+ return new LLSpliterator(this, -1, 0);
+ }
+
+ /** A customized variant of Spliterators.IteratorSpliterator */
+ static final class LLSpliterator implements Spliterator {
+ static final int BATCH_UNIT = 1 << 10; // batch array size increment
+ static final int MAX_BATCH = 1 << 25; // max batch array size;
+ final LinkedList list; // null OK unless traversed
+ Node current; // current node; null until initialized
+ int est; // size estimate; -1 until first needed
+ int expectedModCount; // initialized when est set
+ int batch; // batch size for splits
+
+ LLSpliterator(LinkedList list, int est, int expectedModCount) {
+ this.list = list;
+ this.est = est;
+ this.expectedModCount = expectedModCount;
+ }
+
+ final int getEst() {
+ int s; // force initialization
+ final LinkedList lst;
+ if ((s = est) < 0) {
+ if ((lst = list) == null)
+ s = est = 0;
+ else {
+ expectedModCount = lst.modCount;
+ current = lst.first;
+ s = est = lst.size;
+ }
+ }
+ return s;
+ }
+
+ public long estimateSize() { return (long) getEst(); }
+
+ public Spliterator trySplit() {
+ Node p;
+ int s = getEst();
+ if (s > 1 && (p = current) != null) {
+ int n = batch + BATCH_UNIT;
+ if (n > s)
+ n = s;
+ if (n > MAX_BATCH)
+ n = MAX_BATCH;
+ Object[] a;
+ try {
+ a = new Object[n];
+ } catch (OutOfMemoryError oome) {
+ return null;
+ }
+ int j = 0;
+ do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
+ current = p;
+ batch = j;
+ est = s - j;
+ return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
+ }
+ return null;
+ }
+
+ public void forEachRemaining(Consumer super E> action) {
+ Node p; int n;
+ if (action == null) throw new NullPointerException();
+ if ((n = getEst()) > 0 && (p = current) != null) {
+ current = null;
+ est = 0;
+ do {
+ E e = p.item;
+ p = p.next;
+ action.accept(e);
+ } while (p != null && --n > 0);
+ }
+ if (list.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ }
+
+ public boolean tryAdvance(Consumer super E> action) {
+ Node p;
+ if (action == null) throw new NullPointerException();
+ if (getEst() > 0 && (p = current) != null) {
+ --est;
+ E e = p.item;
+ current = p.next;
+ action.accept(e);
+ if (list.modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ return true;
+ }
+ return false;
+ }
+
+ public int characteristics() {
+ return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
+ }
+ }
+
}
diff --git a/src/share/classes/java/util/PriorityQueue.java b/src/share/classes/java/util/PriorityQueue.java
index dd67a0c5ba4d3c0908586443a3d86292873a82d3..c28647b58bbd0bbeea21199c32f7fd4a4a17f5fc 100644
--- a/src/share/classes/java/util/PriorityQueue.java
+++ b/src/share/classes/java/util/PriorityQueue.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
package java.util;
+import java.util.function.Consumer;
+
/**
* An unbounded priority {@linkplain Queue queue} based on a priority heap.
* The elements of the priority queue are ordered according to their
@@ -56,7 +58,7 @@ package java.util;
* the priority queue in any particular order. If you need ordered
* traversal, consider using {@code Arrays.sort(pq.toArray())}.
*
- * Note that this implementation is not synchronized.
+ *
Note that this implementation is not synchronized.
* Multiple threads should not access a {@code PriorityQueue}
* instance concurrently if any of the threads modifies the queue.
* Instead, use the thread-safe {@link
@@ -92,7 +94,7 @@ public class PriorityQueue extends AbstractQueue
* heap and each descendant d of n, n <= d. The element with the
* lowest value is in queue[0], assuming the queue is nonempty.
*/
- private transient Object[] queue;
+ transient Object[] queue; // non-private to simplify nested class access
/**
* The number of elements in the priority queue.
@@ -109,7 +111,7 @@ public class PriorityQueue extends AbstractQueue
* The number of times this priority queue has been
* structurally modified. See AbstractList for gory details.
*/
- private transient int modCount = 0;
+ transient int modCount = 0; // non-private to simplify nested class access
/**
* Creates a {@code PriorityQueue} with the default initial
@@ -332,9 +334,7 @@ public class PriorityQueue extends AbstractQueue
@SuppressWarnings("unchecked")
public E peek() {
- if (size == 0)
- return null;
- return (E) queue[0];
+ return (size == 0) ? null : (E) queue[0];
}
private int indexOf(Object o) {
@@ -431,15 +431,14 @@ public class PriorityQueue extends AbstractQueue
* 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 queue known to contain only strings.
+ *
Suppose {@code x} is a queue known to contain only strings.
* The following code can be used to dump the queue into a newly
- * allocated array of String:
+ * allocated array of {@code String}:
*
- *
- * String[] y = x.toArray(new String[0]);
+ * {@code 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 queue are to
* be stored, if it is big enough; otherwise, a new array of the
@@ -452,6 +451,7 @@ public class PriorityQueue extends AbstractQueue
*/
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
+ final int size = this.size;
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(queue, size, a.getClass());
@@ -569,15 +569,14 @@ public class PriorityQueue extends AbstractQueue
size = 0;
}
+ @SuppressWarnings("unchecked")
public E poll() {
if (size == 0)
return null;
int s = --size;
modCount++;
- @SuppressWarnings("unchecked")
- E result = (E) queue[0];
- @SuppressWarnings("unchecked")
- E x = (E) queue[s];
+ E result = (E) queue[0];
+ E x = (E) queue[s];
queue[s] = null;
if (s != 0)
siftDown(0, x);
@@ -596,15 +595,15 @@ public class PriorityQueue extends AbstractQueue
* position before i. This fact is used by iterator.remove so as to
* avoid missing traversing elements.
*/
+ @SuppressWarnings("unchecked")
private E removeAt(int i) {
- assert i >= 0 && i < size;
+ // assert i >= 0 && i < size;
modCount++;
int s = --size;
if (s == i) // removed last element
queue[i] = null;
else {
- @SuppressWarnings("unchecked")
- E moved = (E) queue[s];
+ E moved = (E) queue[s];
queue[s] = null;
siftDown(i, moved);
if (queue[i] == moved) {
@@ -649,12 +648,12 @@ public class PriorityQueue extends AbstractQueue
queue[k] = key;
}
+ @SuppressWarnings("unchecked")
private void siftUpUsingComparator(int k, E x) {
while (k > 0) {
int parent = (k - 1) >>> 1;
- @SuppressWarnings("unchecked")
- E e = (E) queue[parent];
- if (comparator.compare(x, e) >= 0)
+ Object e = queue[parent];
+ if (comparator.compare(x, (E) e) >= 0)
break;
queue[k] = e;
k = parent;
@@ -738,8 +737,7 @@ public class PriorityQueue extends AbstractQueue
}
/**
- * Saves the state of the instance to a stream (that
- * is, serializes it).
+ * Saves this queue to a stream (that is, serializes it).
*
* @serialData The length of the array backing the instance is
* emitted (int), followed by all of its elements
@@ -747,7 +745,7 @@ public class PriorityQueue extends AbstractQueue
* @param s the stream
*/
private void writeObject(java.io.ObjectOutputStream s)
- throws java.io.IOException{
+ throws java.io.IOException {
// Write out element count, and any hidden stuff
s.defaultWriteObject();
@@ -783,4 +781,99 @@ public class PriorityQueue extends AbstractQueue
// spec has never explained what that might be.
heapify();
}
+
+ public final Spliterator spliterator() {
+ return new PriorityQueueSpliterator(this, 0, -1, 0);
+ }
+
+ static final class PriorityQueueSpliterator implements Spliterator {
+ /*
+ * This is very similar to ArrayList Spliterator, except for
+ * extra null checks.
+ */
+ private final PriorityQueue