< prev index next >
src/java.base/share/classes/java/util/Scanner.java
Print this page
rev 53930 : 8148917: enhanced-for statement should allow streams
Reviewed-by: XXX
@@ -305,11 +305,11 @@
* </dl>
* <p>Whitespace is not significant in the above regular expressions.
*
* @since 1.5
*/
-public final class Scanner implements Iterator<String>, Closeable {
+public final class Scanner implements Iterator<String>, Closeable, IterableOnce<String> {
// Internal buffer used to hold input
private CharBuffer buf;
// Size of internal character buffer
@@ -370,10 +370,13 @@
private PatternLRUCache patternCache = new PatternLRUCache(7);
// A holder of the last IOException encountered
private IOException lastException;
+ // Whether this Scanner, as IterableOnce, has been consumed
+ private boolean consumed = false;
+
// Number of times this scanner's state has been modified.
// Generally incremented on most public APIs and checked
// within spliterator implementations.
int modCount;
@@ -1478,10 +1481,28 @@
throwFor();
}
}
/**
+ * Returns this Scanner instance. This method exists to implement the
+ * {@link IterableOnce} interface, allowing a Scanner instance to be
+ * used in an enhanced-for ("for each") statement. This method can be
+ * called no more than once on any Scanner instance. The second and
+ * subsequent calls result in an exception.
+ *
+ * @throws IllegalStateException if this method had been called previously
+ * @return this Scanner instance
+ */
+ public Scanner iterator() {
+ if (consumed) {
+ throw new IllegalStateException();
+ }
+ consumed = true;
+ return this;
+ }
+
+ /**
* The remove operation is not supported by this implementation of
* {@code Iterator}.
*
* @throws UnsupportedOperationException if this method is invoked.
* @see java.util.Iterator
< prev index next >