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 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 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 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 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 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 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 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 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 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 action) { c.forEach(action); @@ -1122,6 +1128,11 @@ public class Collections { public boolean removeIf(Predicate 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 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 action) {
-            synchronized (mutex) {c.forEach(action);}
+        public void forEach(Consumer consumer) {
+            synchronized (mutex) {c.forEach(consumer);}
         }
         @Override
         public boolean removeIf(Predicate 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 action) {
-            c.forEach(action);
-        }
+        public void forEach(Consumer action) {c.forEach(action);}
         @Override
         public boolean removeIf(Predicate 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 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 action) {
+            Objects.requireNonNull(action);
+        }
     }
 
     /**
@@ -3474,6 +3505,7 @@ public class Collections {
             return a;
         }
 
+        // Override default methods in Collection
         @Override
         public void forEach(Consumer 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 action) {
             Objects.requireNonNull(action);
         }
+
         @Override
         public boolean removeIf(Predicate 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 action) {
-            Objects.requireNonNull(action);
-        }
         @Override
         public boolean removeIf(Predicate filter) {
             Objects.requireNonNull(filter);
@@ -3688,6 +3723,15 @@ public class Collections {
             Objects.requireNonNull(c);
         }
 
+        // Override default methods in Collection
+        @Override
+        public void forEach(Consumer 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 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 consumer) {
+                Objects.requireNonNull(consumer);
+                if (est > 0) {
+                    est--;
+                    consumer.accept(element);
+                    return true;
+                }
+                return false;
+            }
+
+            @Override
+            public void forEachRemaining(Consumer 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 action) {
             action.accept(element);
         }
         @Override
+        public Spliterator spliterator() {
+            return singletonSpliterator(element);
+        }
+        @Override
         public boolean removeIf(Predicate filter) {
             throw new UnsupportedOperationException();
         }
@@ -3916,6 +4019,7 @@ public class Collections {
             return element;
         }
 
+        // Override default methods for Collection
         @Override
         public void forEach(Consumer action) {
             action.accept(element);
@@ -3931,6 +4035,10 @@ public class Collections {
         @Override
         public void sort(Comparator 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 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 action) {
-            q.forEach(action);
-        }
+        public void forEach(Consumer action) {q.forEach(action);}
+        @Override
+        public Spliterator spliterator() {return q.spliterator();}
         @Override
         public boolean removeIf(Predicate 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 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 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 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 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> 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> 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 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 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 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 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> 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> 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 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 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 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 pq; + private int index; // current index, modified on advance/split + private int fence; // -1 until first use + private int expectedModCount; // initialized when fence set + + /** Creates new spliterator covering the given range */ + PriorityQueueSpliterator(PriorityQueue pq, int origin, int fence, + int expectedModCount) { + this.pq = pq; + this.index = origin; + this.fence = fence; + this.expectedModCount = expectedModCount; + } + + private int getFence() { // initialize fence to size on first use + int hi; + if ((hi = fence) < 0) { + expectedModCount = pq.modCount; + hi = fence = pq.size; + } + return hi; + } + + public PriorityQueueSpliterator trySplit() { + int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; + return (lo >= mid) ? null : + new PriorityQueueSpliterator(pq, lo, index = mid, + expectedModCount); + } + + @SuppressWarnings("unchecked") + public void forEachRemaining(Consumer action) { + int i, hi, mc; // hoist accesses and checks from loop + PriorityQueue q; Object[] a; + if (action == null) + throw new NullPointerException(); + if ((q = pq) != null && (a = q.queue) != null) { + if ((hi = fence) < 0) { + mc = q.modCount; + hi = q.size; + } + else + mc = expectedModCount; + if ((i = index) >= 0 && (index = hi) <= a.length) { + for (E e;; ++i) { + if (i < hi) { + if ((e = (E) a[i]) == null) // must be CME + break; + action.accept(e); + } + else if (q.modCount != mc) + break; + else + return; + } + } + } + throw new ConcurrentModificationException(); + } + + public boolean tryAdvance(Consumer action) { + if (action == null) + throw new NullPointerException(); + int hi = getFence(), lo = index; + if (lo >= 0 && lo < hi) { + index = lo + 1; + @SuppressWarnings("unchecked") E e = (E)pq.queue[lo]; + if (e == null) + throw new ConcurrentModificationException(); + action.accept(e); + if (pq.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + return false; + } + + public long estimateSize() { + return (long) (getFence() - index); + } + + public int characteristics() { + return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL; + } + } } diff --git a/src/share/classes/java/util/TreeMap.java b/src/share/classes/java/util/TreeMap.java index 14d75e7187be773620b832b4a6502222e1c06e69..c96fa41652dd26972d12525184459c8ce58f8622 100644 --- a/src/share/classes/java/util/TreeMap.java +++ b/src/share/classes/java/util/TreeMap.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 @@ -25,6 +25,8 @@ package java.util; +import java.util.function.Consumer; + /** * A Red-Black tree based {@link NavigableMap} implementation. * The map is sorted according to the {@linkplain Comparable natural @@ -971,6 +973,10 @@ public class TreeMap public void clear() { TreeMap.this.clear(); } + + public Spliterator spliterator() { + return new ValueSpliterator(TreeMap.this, null, null, 0, -1, 0); + } } class EntrySet extends AbstractSet> { @@ -1007,6 +1013,10 @@ public class TreeMap public void clear() { TreeMap.this.clear(); } + + public Spliterator> spliterator() { + return new EntrySpliterator(TreeMap.this, null, null, 0, -1, 0); + } } /* @@ -1090,6 +1100,10 @@ public class TreeMap public NavigableSet descendingSet() { return new KeySet<>(m.descendingMap()); } + + public Spliterator spliterator() { + return keySpliteratorFor(m); + } } /** @@ -1389,6 +1403,8 @@ public class TreeMap /** Returns ascending iterator from the perspective of this submap */ abstract Iterator keyIterator(); + abstract Spliterator keySpliterator(); + /** Returns descending iterator from the perspective of this submap */ abstract Iterator descendingKeyIterator(); @@ -1650,7 +1666,23 @@ public class TreeMap } } - final class SubMapKeyIterator extends SubMapIterator { + final class DescendingSubMapEntryIterator extends SubMapIterator> { + DescendingSubMapEntryIterator(TreeMap.Entry last, + TreeMap.Entry fence) { + super(last, fence); + } + + public Map.Entry next() { + return prevEntry(); + } + public void remove() { + removeDescending(); + } + } + + // Implement minimal Spliterator as KeySpliterator backup + final class SubMapKeyIterator extends SubMapIterator + implements Spliterator { SubMapKeyIterator(TreeMap.Entry first, TreeMap.Entry fence) { super(first, fence); @@ -1661,23 +1693,34 @@ public class TreeMap public void remove() { removeAscending(); } - } - - final class DescendingSubMapEntryIterator extends SubMapIterator> { - DescendingSubMapEntryIterator(TreeMap.Entry last, - TreeMap.Entry fence) { - super(last, fence); + public Spliterator trySplit() { + return null; } - - public Map.Entry next() { - return prevEntry(); + public void forEachRemaining(Consumer action) { + while (hasNext()) + action.accept(next()); } - public void remove() { - removeDescending(); + public boolean tryAdvance(Consumer action) { + if (hasNext()) { + action.accept(next()); + return true; + } + return false; + } + public long estimateSize() { + return Long.MAX_VALUE; + } + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.ORDERED | + Spliterator.SORTED; + } + public final Comparator getComparator() { + return NavigableSubMap.this.comparator(); } } - final class DescendingSubMapKeyIterator extends SubMapIterator { + final class DescendingSubMapKeyIterator extends SubMapIterator + implements Spliterator { DescendingSubMapKeyIterator(TreeMap.Entry last, TreeMap.Entry fence) { super(last, fence); @@ -1688,6 +1731,26 @@ public class TreeMap public void remove() { removeDescending(); } + public Spliterator trySplit() { + return null; + } + public void forEachRemaining(Consumer action) { + while (hasNext()) + action.accept(next()); + } + public boolean tryAdvance(Consumer action) { + if (hasNext()) { + action.accept(next()); + return true; + } + return false; + } + public long estimateSize() { + return Long.MAX_VALUE; + } + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.ORDERED; + } } } @@ -1747,6 +1810,10 @@ public class TreeMap return new SubMapKeyIterator(absLowest(), absHighFence()); } + Spliterator keySpliterator() { + return new SubMapKeyIterator(absLowest(), absHighFence()); + } + Iterator descendingKeyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } @@ -1828,6 +1895,10 @@ public class TreeMap return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } + Spliterator keySpliterator() { + return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); + } + Iterator descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } @@ -2444,4 +2515,407 @@ public class TreeMap level++; return level; } + + /** + * Currently, we support Spliterator-based versions only for the + * full map, in either plain of descending form, otherwise relying + * on defaults because size estimation for submaps would dominate + * costs. The type tests needed to check these for key views are + * not very nice but avoid disrupting existing class + * structures. Callers must use plain default spliterators if this + * returns null. + */ + static Spliterator keySpliteratorFor(NavigableMap m) { + if (m instanceof TreeMap) { + @SuppressWarnings("unchecked") TreeMap t = + (TreeMap) m; + return t.keySpliterator(); + } + if (m instanceof DescendingSubMap) { + @SuppressWarnings("unchecked") DescendingSubMap dm = + (DescendingSubMap) m; + TreeMap tm = dm.m; + if (dm == tm.descendingMap) { + @SuppressWarnings("unchecked") TreeMap t = + (TreeMap) tm; + return t.descendingKeySpliterator(); + } + } + @SuppressWarnings("unchecked") NavigableSubMap sm = + (NavigableSubMap) m; + return sm.keySpliterator(); + } + + final Spliterator keySpliterator() { + return new KeySpliterator(this, null, null, 0, -1, 0); + } + + final Spliterator descendingKeySpliterator() { + return new DescendingKeySpliterator(this, null, null, 0, -2, 0); + } + + /** + * Base class for spliterators. Iteration starts at a given + * origin and continues up to but not including a given fence (or + * null for end). At top-level, for ascending cases, the first + * split uses the root as left-fence/right-origin. From there, + * right-hand splits replace the current fence with its left + * child, also serving as origin for the split-off spliterator. + * Left-hands are symmetric. Descending versions place the origin + * at the end and invert ascending split rules. This base class + * is non-commital about directionality, or whether the top-level + * spliterator covers the whole tree. This means that the actual + * split mechanics are located in subclasses. Some of the subclass + * trySplit methods are identical (except for return types), but + * not nicely factorable. + * + * Currently, subclass versions exist only for the full map + * (including descending keys via its descendingMap). Others are + * possible but currently not worthwhile because submaps require + * O(n) computations to determine size, which substantially limits + * potential speed-ups of using custom Spliterators versus default + * mechanics. + * + * To boostrap initialization, external constructors use + * negative size estimates: -1 for ascend, -2 for descend. + */ + static class TreeMapSpliterator { + final TreeMap tree; + TreeMap.Entry current; // traverser; initially first node in range + TreeMap.Entry fence; // one past last, or null + int side; // 0: top, -1: is a left split, +1: right + int est; // size estimate (exact only for top-level) + int expectedModCount; // for CME checks + + TreeMapSpliterator(TreeMap tree, + TreeMap.Entry origin, TreeMap.Entry fence, + int side, int est, int expectedModCount) { + this.tree = tree; + this.current = origin; + this.fence = fence; + this.side = side; + this.est = est; + this.expectedModCount = expectedModCount; + } + + final int getEstimate() { // force initialization + int s; TreeMap t; + if ((s = est) < 0) { + if ((t = tree) != null) { + current = (s == -1) ? t.getFirstEntry() : t.getLastEntry(); + s = est = t.size; + expectedModCount = t.modCount; + } + else + s = est = 0; + } + return s; + } + + public final long estimateSize() { + return (long)getEstimate(); + } + } + + static final class KeySpliterator + extends TreeMapSpliterator + implements Spliterator { + KeySpliterator(TreeMap tree, + TreeMap.Entry origin, TreeMap.Entry fence, + int side, int est, int expectedModCount) { + super(tree, origin, fence, side, est, expectedModCount); + } + + public KeySpliterator trySplit() { + if (est < 0) + getEstimate(); // force initialization + int d = side; + TreeMap.Entry e = current, f = fence, + s = ((e == null || e == f) ? null : // empty + (d == 0) ? tree.root : // was top + (d > 0) ? e.right : // was right + (d < 0 && f != null) ? f.left : // was left + null); + if (s != null && s != e && s != f && + tree.compare(e.key, s.key) < 0) { // e not already past s + side = 1; + return new KeySpliterator<> + (tree, e, current = s, -1, est >>>= 1, expectedModCount); + } + return null; + } + + public void forEachRemaining(Consumer action) { + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + TreeMap.Entry f = fence, e, p, pl; + if ((e = current) != null && e != f) { + current = f; // exhaust + do { + action.accept(e.key); + if ((p = e.right) != null) { + while ((pl = p.left) != null) + p = pl; + } + else { + while ((p = e.parent) != null && e == p.right) + e = p; + } + } while ((e = p) != null && e != f); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + } + } + + public boolean tryAdvance(Consumer action) { + TreeMap.Entry e; + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + if ((e = current) == null || e == fence) + return false; + current = successor(e); + action.accept(e.key); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + + public int characteristics() { + return (side == 0 ? Spliterator.SIZED : 0) | + Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED; + } + + public final Comparator getComparator() { + return tree.comparator; + } + + } + + static final class DescendingKeySpliterator + extends TreeMapSpliterator + implements Spliterator { + DescendingKeySpliterator(TreeMap tree, + TreeMap.Entry origin, TreeMap.Entry fence, + int side, int est, int expectedModCount) { + super(tree, origin, fence, side, est, expectedModCount); + } + + public DescendingKeySpliterator trySplit() { + if (est < 0) + getEstimate(); // force initialization + int d = side; + TreeMap.Entry e = current, f = fence, + s = ((e == null || e == f) ? null : // empty + (d == 0) ? tree.root : // was top + (d < 0) ? e.left : // was left + (d > 0 && f != null) ? f.right : // was right + null); + if (s != null && s != e && s != f && + tree.compare(e.key, s.key) > 0) { // e not already past s + side = 1; + return new DescendingKeySpliterator<> + (tree, e, current = s, -1, est >>>= 1, expectedModCount); + } + return null; + } + + public void forEachRemaining(Consumer action) { + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + TreeMap.Entry f = fence, e, p, pr; + if ((e = current) != null && e != f) { + current = f; // exhaust + do { + action.accept(e.key); + if ((p = e.left) != null) { + while ((pr = p.right) != null) + p = pr; + } + else { + while ((p = e.parent) != null && e == p.left) + e = p; + } + } while ((e = p) != null && e != f); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + } + } + + public boolean tryAdvance(Consumer action) { + TreeMap.Entry e; + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + if ((e = current) == null || e == fence) + return false; + current = predecessor(e); + action.accept(e.key); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + + public int characteristics() { + return (side == 0 ? Spliterator.SIZED : 0) | + Spliterator.DISTINCT | Spliterator.ORDERED; + } + } + + static final class ValueSpliterator + extends TreeMapSpliterator + implements Spliterator { + ValueSpliterator(TreeMap tree, + TreeMap.Entry origin, TreeMap.Entry fence, + int side, int est, int expectedModCount) { + super(tree, origin, fence, side, est, expectedModCount); + } + + public ValueSpliterator trySplit() { + if (est < 0) + getEstimate(); // force initialization + int d = side; + TreeMap.Entry e = current, f = fence, + s = ((e == null || e == f) ? null : // empty + (d == 0) ? tree.root : // was top + (d > 0) ? e.right : // was right + (d < 0 && f != null) ? f.left : // was left + null); + if (s != null && s != e && s != f && + tree.compare(e.key, s.key) < 0) { // e not already past s + side = 1; + return new ValueSpliterator<> + (tree, e, current = s, -1, est >>>= 1, expectedModCount); + } + return null; + } + + public void forEachRemaining(Consumer action) { + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + TreeMap.Entry f = fence, e, p, pl; + if ((e = current) != null && e != f) { + current = f; // exhaust + do { + action.accept(e.value); + if ((p = e.right) != null) { + while ((pl = p.left) != null) + p = pl; + } + else { + while ((p = e.parent) != null && e == p.right) + e = p; + } + } while ((e = p) != null && e != f); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + } + } + + public boolean tryAdvance(Consumer action) { + TreeMap.Entry e; + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + if ((e = current) == null || e == fence) + return false; + current = successor(e); + action.accept(e.value); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + + public int characteristics() { + return (side == 0 ? Spliterator.SIZED : 0); + } + } + + static final class EntrySpliterator + extends TreeMapSpliterator + implements Spliterator> { + EntrySpliterator(TreeMap tree, + TreeMap.Entry origin, TreeMap.Entry fence, + int side, int est, int expectedModCount) { + super(tree, origin, fence, side, est, expectedModCount); + } + + public EntrySpliterator trySplit() { + if (est < 0) + getEstimate(); // force initialization + int d = side; + TreeMap.Entry e = current, f = fence, + s = ((e == null || e == f) ? null : // empty + (d == 0) ? tree.root : // was top + (d > 0) ? e.right : // was right + (d < 0 && f != null) ? f.left : // was left + null); + if (s != null && s != e && s != f && + tree.compare(e.key, s.key) < 0) { // e not already past s + side = 1; + return new EntrySpliterator<> + (tree, e, current = s, -1, est >>>= 1, expectedModCount); + } + return null; + } + + public void forEachRemaining(Consumer> action) { + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + TreeMap.Entry f = fence, e, p, pl; + if ((e = current) != null && e != f) { + current = f; // exhaust + do { + action.accept(e); + if ((p = e.right) != null) { + while ((pl = p.left) != null) + p = pl; + } + else { + while ((p = e.parent) != null && e == p.right) + e = p; + } + } while ((e = p) != null && e != f); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + } + } + + public boolean tryAdvance(Consumer> action) { + TreeMap.Entry e; + if (action == null) + throw new NullPointerException(); + if (est < 0) + getEstimate(); // force initialization + if ((e = current) == null || e == fence) + return false; + current = successor(e); + action.accept(e); + if (tree.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + + public int characteristics() { + return (side == 0 ? Spliterator.SIZED : 0) | + Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED; + } + + @Override + public Comparator> getComparator() { + return tree.comparator != null ? + Comparators.byKey(tree.comparator) : null; + } + } } diff --git a/src/share/classes/java/util/TreeSet.java b/src/share/classes/java/util/TreeSet.java index a369af25c6c51c66c09a22c1880f5470c3333a54..9484d5b87c7835faac31c89f2c810d8a06b05763 100644 --- a/src/share/classes/java/util/TreeSet.java +++ b/src/share/classes/java/util/TreeSet.java @@ -533,5 +533,9 @@ public class TreeSet extends AbstractSet tm.readTreeSet(size, s, PRESENT); } + public Spliterator spliterator() { + return TreeMap.keySpliteratorFor(m); + } + private static final long serialVersionUID = -2479143000061671589L; } diff --git a/src/share/classes/java/util/Vector.java b/src/share/classes/java/util/Vector.java index ef02e74eeabea69074232e2a14198f99867ab6fc..1d742c801e5d154d81c541681d0873b0cc083f44 100644 --- a/src/share/classes/java/util/Vector.java +++ b/src/share/classes/java/util/Vector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 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 @@ -29,6 +29,8 @@ import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; +import java.util.function.Consumer; + /** * The {@code Vector} class implements a growable array of * objects. Like an array, it contains components that can be @@ -1155,6 +1157,28 @@ public class Vector lastRet = -1; } + @Override + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); + synchronized (Vector.this) { + final int size = Vector.this.elementCount; + int i = cursor; + if (i >= size) { + return; + } + final Object[] elementData = Vector.this.elementData; + if (i >= elementData.length) { + throw new ConcurrentModificationException(); + } + while (i != size && modCount == expectedModCount) { + action.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(); @@ -1298,4 +1322,96 @@ public class Vector } modCount++; } + + @Override + public Spliterator spliterator() { + return new VectorSpliterator<>(this, null, 0, -1, 0); + } + + /** Similar to ArrayList Spliterator */ + static final class VectorSpliterator implements Spliterator { + private final Vector list; + private Object[] array; + 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 */ + VectorSpliterator(Vector list, Object[] array, int origin, int fence, + int expectedModCount) { + this.list = list; + this.array = array; + this.index = origin; + this.fence = fence; + this.expectedModCount = expectedModCount; + } + + private int getFence() { // initialize on first use + int hi; + if ((hi = fence) < 0) { + synchronized(list) { + array = list.elementData; + expectedModCount = list.modCount; + hi = fence = list.elementCount; + } + } + return hi; + } + + public Spliterator trySplit() { + int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; + return (lo >= mid) ? null : + new VectorSpliterator(list, array, lo, index = mid, + expectedModCount); + } + + @SuppressWarnings("unchecked") + public boolean tryAdvance(Consumer action) { + int i; + if (action == null) + throw new NullPointerException(); + if (getFence() > (i = index)) { + index = i + 1; + action.accept((E)array[i]); + if (list.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + return false; + } + + @SuppressWarnings("unchecked") + public void forEachRemaining(Consumer action) { + int i, hi; // hoist accesses and checks from loop + Vector lst; Object[] a; + if (action == null) + throw new NullPointerException(); + if ((lst = list) != null) { + if ((hi = fence) < 0) { + synchronized(lst) { + expectedModCount = lst.modCount; + a = array = lst.elementData; + hi = fence = lst.elementCount; + } + } + else + a = array; + if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { + while (i < hi) + action.accept((E) a[i++]); + if (lst.modCount == expectedModCount) + return; + } + } + throw new ConcurrentModificationException(); + } + + public long estimateSize() { + return (long) (getFence() - index); + } + + public int characteristics() { + return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; + } + } } diff --git a/src/share/classes/java/util/WeakHashMap.java b/src/share/classes/java/util/WeakHashMap.java index eb24a18fc44c725e2652eab5e549f5162c47fa16..77f9e094c1ae5090e3955525c42986812b7e6236 100644 --- a/src/share/classes/java/util/WeakHashMap.java +++ b/src/share/classes/java/util/WeakHashMap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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.lang.ref.WeakReference; import java.lang.ref.ReferenceQueue; +import java.util.function.Consumer; /** @@ -898,6 +900,10 @@ public class WeakHashMap public void clear() { WeakHashMap.this.clear(); } + + public Spliterator spliterator() { + return new KeySpliterator<>(WeakHashMap.this, 0, -1, 0, 0); + } } /** @@ -934,6 +940,10 @@ public class WeakHashMap public void clear() { WeakHashMap.this.clear(); } + + public Spliterator spliterator() { + return new ValueSpliterator<>(WeakHashMap.this, 0, -1, 0, 0); + } } /** @@ -994,5 +1004,288 @@ public class WeakHashMap public T[] toArray(T[] a) { return deepCopy().toArray(a); } + + public Spliterator> spliterator() { + return new EntrySpliterator<>(WeakHashMap.this, 0, -1, 0, 0); + } + } + + /** + * Similar form as other hash Spliterators, but skips dead + * elements. + */ + static class WeakHashMapSpliterator { + final WeakHashMap map; + WeakHashMap.Entry current; // current node + 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; // for comodification checks + + WeakHashMapSpliterator(WeakHashMap 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) { + WeakHashMap 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 WeakHashMapSpliterator + implements Spliterator { + KeySpliterator(WeakHashMap 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) ? null : + new KeySpliterator(map, lo, index = mid, est >>>= 1, + expectedModCount); + } + + public void forEachRemaining(Consumer action) { + int i, hi, mc; + if (action == null) + throw new NullPointerException(); + WeakHashMap m = map; + WeakHashMap.Entry[] tab = 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 < hi) { + index = hi; + WeakHashMap.Entry p = current; + do { + if (p == null) + p = tab[i++]; + else { + Object x = p.get(); + p = p.next; + if (x != null) { + @SuppressWarnings("unchecked") K k = + (K) WeakHashMap.unmaskNull(x); + action.accept(k); + } + } + } while (p != null || i < hi); + } + if (m.modCount != mc) + throw new ConcurrentModificationException(); + } + + public boolean tryAdvance(Consumer action) { + int hi; + if (action == null) + throw new NullPointerException(); + WeakHashMap.Entry[] tab = map.table; + if (tab.length >= (hi = getFence()) && index >= 0) { + while (current != null || index < hi) { + if (current == null) + current = tab[index++]; + else { + Object x = current.get(); + current = current.next; + if (x != null) { + @SuppressWarnings("unchecked") K k = + (K) WeakHashMap.unmaskNull(x); + action.accept(k); + if (map.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + } + } + } + return false; + } + + public int characteristics() { + return Spliterator.DISTINCT; + } + } + + static final class ValueSpliterator + extends WeakHashMapSpliterator + implements Spliterator { + ValueSpliterator(WeakHashMap 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) ? null : + new ValueSpliterator(map, lo, index = mid, est >>>= 1, + expectedModCount); + } + + public void forEachRemaining(Consumer action) { + int i, hi, mc; + if (action == null) + throw new NullPointerException(); + WeakHashMap m = map; + WeakHashMap.Entry[] tab = 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 < hi) { + index = hi; + WeakHashMap.Entry p = current; + do { + if (p == null) + p = tab[i++]; + else { + Object x = p.get(); + V v = p.value; + p = p.next; + if (x != null) + action.accept(v); + } + } while (p != null || i < hi); + } + if (m.modCount != mc) + throw new ConcurrentModificationException(); + } + + public boolean tryAdvance(Consumer action) { + int hi; + if (action == null) + throw new NullPointerException(); + WeakHashMap.Entry[] tab = map.table; + if (tab.length >= (hi = getFence()) && index >= 0) { + while (current != null || index < hi) { + if (current == null) + current = tab[index++]; + else { + Object x = current.get(); + V v = current.value; + current = current.next; + if (x != null) { + action.accept(v); + if (map.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + } + } + } + return false; + } + + public int characteristics() { + return 0; + } + } + + static final class EntrySpliterator + extends WeakHashMapSpliterator + implements Spliterator> { + EntrySpliterator(WeakHashMap 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) ? null : + new EntrySpliterator(map, lo, index = mid, est >>>= 1, + expectedModCount); + } + + + public void forEachRemaining(Consumer> action) { + int i, hi, mc; + if (action == null) + throw new NullPointerException(); + WeakHashMap m = map; + WeakHashMap.Entry[] tab = 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 < hi) { + index = hi; + WeakHashMap.Entry p = current; + do { + if (p == null) + p = tab[i++]; + else { + Object x = p.get(); + V v = p.value; + p = p.next; + if (x != null) { + @SuppressWarnings("unchecked") K k = + (K) WeakHashMap.unmaskNull(x); + action.accept + (new AbstractMap.SimpleImmutableEntry(k, v)); + } + } + } while (p != null || i < hi); + } + if (m.modCount != mc) + throw new ConcurrentModificationException(); + } + + public boolean tryAdvance(Consumer> action) { + int hi; + if (action == null) + throw new NullPointerException(); + WeakHashMap.Entry[] tab = map.table; + if (tab.length >= (hi = getFence()) && index >= 0) { + while (current != null || index < hi) { + if (current == null) + current = tab[index++]; + else { + Object x = current.get(); + V v = current.value; + current = current.next; + if (x != null) { + @SuppressWarnings("unchecked") K k = + (K) WeakHashMap.unmaskNull(x); + action.accept + (new AbstractMap.SimpleImmutableEntry(k, v)); + if (map.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + } + } + } + return false; + } + + public int characteristics() { + return Spliterator.DISTINCT; + } } + } diff --git a/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java b/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java index 046cfa079f1f0877cf373bbebb490ff7d91c0204..cb5ffa90ed3daa4bc5be808a54f1e120495f59ee 100644 --- a/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java +++ b/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java @@ -184,6 +184,8 @@ public class SpliteratorTraversingAndSplittingTest { @Override public boolean tryAdvance(Consumer action) { + if (action == null) + throw new NullPointerException(); if (it.hasNext()) { action.accept(it.next()); return true; @@ -193,7 +195,7 @@ public class SpliteratorTraversingAndSplittingTest { } } } - db.add("new Spliterators.AbstractAdvancingSpliterator()", + db.add("new Spliterators.AbstractSpliterator()", () -> new SpliteratorFromIterator(exp.iterator(), exp.size())); // Collections @@ -370,7 +372,28 @@ public class SpliteratorTraversingAndSplittingTest { db.addCollection(c -> Collections.singletonList(exp.get(0))); } - // @@@ Collections.synchronized/unmodifiable/checked wrappers + // Collections.synchronized/unmodifiable/checked wrappers + db.addCollection(Collections::unmodifiableCollection); + db.addCollection(c -> Collections.unmodifiableSet(new HashSet<>(c))); + db.addCollection(c -> Collections.unmodifiableSortedSet(new TreeSet<>(c))); + db.addList(c -> Collections.unmodifiableList(new ArrayList<>(c))); + db.addMap(Collections::unmodifiableMap); + db.addMap(m -> Collections.unmodifiableSortedMap(new TreeMap<>(m))); + + db.addCollection(Collections::synchronizedCollection); + db.addCollection(c -> Collections.synchronizedSet(new HashSet<>(c))); + db.addCollection(c -> Collections.synchronizedSortedSet(new TreeSet<>(c))); + db.addList(c -> Collections.synchronizedList(new ArrayList<>(c))); + db.addMap(Collections::synchronizedMap); + db.addMap(m -> Collections.synchronizedSortedMap(new TreeMap<>(m))); + + db.addCollection(c -> Collections.checkedCollection(c, Integer.class)); + db.addCollection(c -> Collections.checkedQueue(new ArrayDeque<>(c), Integer.class)); + db.addCollection(c -> Collections.checkedSet(new HashSet<>(c), Integer.class)); + db.addCollection(c -> Collections.checkedSortedSet(new TreeSet<>(c), Integer.class)); + db.addList(c -> Collections.checkedList(new ArrayList<>(c), Integer.class)); + db.addMap(c -> Collections.checkedMap(c, Integer.class, Integer.class)); + db.addMap(m -> Collections.checkedSortedMap(new TreeMap<>(m), Integer.class, Integer.class)); // Maps @@ -400,6 +423,13 @@ public class SpliteratorTraversingAndSplittingTest { return Collections.unmodifiableList(exp); } + @Test(dataProvider = "Spliterator") + @SuppressWarnings({"unchecked", "rawtypes"}) + public void testNullPointerException(String description, Collection exp, Supplier s) { + executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null)); + executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null)); + } + @Test(dataProvider = "Spliterator") @SuppressWarnings({"unchecked", "rawtypes"}) public void testForEach(String description, Collection exp, Supplier s) { @@ -507,6 +537,8 @@ public class SpliteratorTraversingAndSplittingTest { @Override public boolean tryAdvance(IntConsumer action) { + if (action == null) + throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; @@ -552,6 +584,12 @@ public class SpliteratorTraversingAndSplittingTest { return b -> new BoxingAdapter(b); } + @Test(dataProvider = "Spliterator.OfInt") + public void testIntNullPointerException(String description, Collection exp, Supplier s) { + executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((IntConsumer) null)); + executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((IntConsumer) null)); + } + @Test(dataProvider = "Spliterator.OfInt") public void testIntForEach(String description, Collection exp, Supplier s) { testForEach(exp, s, intBoxingConsumer()); @@ -652,6 +690,8 @@ public class SpliteratorTraversingAndSplittingTest { @Override public boolean tryAdvance(LongConsumer action) { + if (action == null) + throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; @@ -704,6 +744,12 @@ public class SpliteratorTraversingAndSplittingTest { return b -> new BoxingAdapter(b); } + @Test(dataProvider = "Spliterator.OfLong") + public void testLongNullPointerException(String description, Collection exp, Supplier s) { + executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((LongConsumer) null)); + executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((LongConsumer) null)); + } + @Test(dataProvider = "Spliterator.OfLong") public void testLongForEach(String description, Collection exp, Supplier s) { testForEach(exp, s, longBoxingConsumer()); @@ -804,6 +850,8 @@ public class SpliteratorTraversingAndSplittingTest { @Override public boolean tryAdvance(DoubleConsumer action) { + if (action == null) + throw new NullPointerException(); if (index < a.length) { action.accept(a[index++]); return true; @@ -856,6 +904,12 @@ public class SpliteratorTraversingAndSplittingTest { return b -> new BoxingAdapter(b); } + @Test(dataProvider = "Spliterator.OfDouble") + public void testDoubleNullPointerException(String description, Collection exp, Supplier s) { + executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((DoubleConsumer) null)); + executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((DoubleConsumer) null)); + } + @Test(dataProvider = "Spliterator.OfDouble") public void testDoubleForEach(String description, Collection exp, Supplier s) { testForEach(exp, s, doubleBoxingConsumer()); @@ -1057,8 +1111,8 @@ public class SpliteratorTraversingAndSplittingTest { } private static > void visit(int depth, int curLevel, - List dest, S spliterator, UnaryOperator> boxingAdapter, - int rootCharacteristics, boolean useTryAdvance) { + List dest, S spliterator, UnaryOperator> boxingAdapter, + int rootCharacteristics, boolean useTryAdvance) { if (curLevel < depth) { long beforeSize = spliterator.getExactSizeIfKnown(); Spliterator split = spliterator.trySplit(); @@ -1187,13 +1241,13 @@ public class SpliteratorTraversingAndSplittingTest { assertTrue(leftSplit.estimateSize() < parentEstimateSize, String.format("Left split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); assertTrue(parentAndRightSplit.estimateSize() < parentEstimateSize, - String.format("Right split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); + String.format("Right split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); } else { assertTrue(leftSplit.estimateSize() <= parentEstimateSize, - String.format("Left split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); + String.format("Left split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); assertTrue(parentAndRightSplit.estimateSize() <= parentEstimateSize, - String.format("Right split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); + String.format("Right split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); } long leftSize = leftSplit.getExactSizeIfKnown(); @@ -1254,4 +1308,22 @@ public class SpliteratorTraversingAndSplittingTest { }); return result; } + + private void executeAndCatch(Class expected, Runnable r) { + Exception caught = null; + try { + r.run(); + } + catch (Exception e) { + caught = e; + } + + assertNotNull(caught, + String.format("No Exception was thrown, expected an Exception of %s to be thrown", + expected.getName())); + assertTrue(expected.isInstance(caught), + String.format("Exception thrown %s not an instance of %s", + caught.getClass().getName(), expected.getName())); + } + }