# HG changeset patch # User redestad # Date 1431791694 -7200 # Sat May 16 17:54:54 2015 +0200 # Node ID 91b7b459b3025618f39dc5105ca496ad31db3e53 # Parent effdf04cfcecd47f3155299d6140fd851ef7d873 [mq]: enumable diff --git a/src/java.base/share/classes/java/util/Enumeration.java b/src/java.base/share/classes/java/util/Enumeration.java --- a/src/java.base/share/classes/java/util/Enumeration.java +++ b/src/java.base/share/classes/java/util/Enumeration.java @@ -58,7 +58,7 @@ * @author Lee Boynton * @since 1.0 */ -public interface Enumeration { +public interface Enumeration extends Iterable { /** * Tests if this enumeration contains more elements. * @@ -76,4 +76,58 @@ * @exception NoSuchElementException if no more elements exist. */ E nextElement(); + + /** + * Returns an {@link Iterator} whose elements are the same as the + * elements of this {@code Enumeration}. The results are undefined + * if this method is called more than once, or if this Enumeration's + * other methods are called after {@code asIterator} has been called. + * + * @apiNote + * This method is intended to help adapt code that produces + * {@code Enumeration} instances to code that consumes {@code Iterator} + * or {@code Iterable} instances. For example, the + * {@link java.security.PermissionCollection PermissionCollection.elements()} + * method returns an {@code Enumeration}. This can be adapted + * for use in an enhanced-for loop as follows: + * + *
{@code
+     *     PermissionCollection pc = ... ;
+     *     for (Permission p : pc.elements()) {
+     *         doSomethingWithPermission(p);
+     *     }
+     * }
+ * + * A {@code Stream} could be created from an + * {@code Enumeration} as follows: + * + *
{@code
+     *     Stream permsStream = StreamSupport.stream(
+     *         Spliterators.spliteratorUnknownSize(
+     *             pc.elements().iterator(),
+     *             Spliterator.ORDERED | Spliterator.IMMUTABLE),
+     *         false);
+     * }
+ * + * @implSpec + * The returned Iterator's {@link Iterator#hasNext hasNext} method calls and returns + * the value from this Enumeration's {@code hasMoreElements} method; its + * {@link Iterator#next next} method calls and returns the value from this Enumeration's + * {@code nextElement} method; and its {@link Iterator#remove remove} method throws + * {@code UnsupportedOperationException}. + * + * @return an Iterator derived from this Enumeration + * + * @since 1.9 + */ + default Iterator asIterator() { + return new Iterator() { + @Override public boolean hasNext() { + return Enumeration.this.hasMoreElements(); + } + @Override public E next() { + return Enumeration.this.nextElement(); + } + }; + } }