--- /dev/null 2013-09-26 12:31:35.724641065 +0400 +++ new/src/share/demo/extension-methods/ArrayIterator.java 2013-09-27 18:40:59.217577614 +0400 @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + */ + + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * The code sample illustrates usage default methods in the JDK 8. Most + * implementations of Iterator don’t provide a useful remove(), however, they + * still have to implement this method just to throw + * UnsupportedOperationException. With default method, we could provide the same + * "default" behavior in interface Iterator itself + */ +public class ArrayIterator { + + public static Iterator iterator(final E[] array) { + return new Iterator() { + /** + * Initial array + * + */ + private final E[] srcArray = array; + + /** + * Index of the current position + * + */ + private int index = 0; + + @Override + public boolean hasNext() { + return (index < srcArray.length); + } + + @Override + public E next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return srcArray[index++]; + } + + /** + * We do not need to override this method in JDK 8 + */ + //@Override + //public void remove() { + // throw UnsupportedOperationException("Arrays don't support remove") + //} + }; + } + + public static void main(String args[]) { + Iterator it = ArrayIterator.iterator(new String[]{"one", "two", "three"}); + + while (it.hasNext()) { + System.out.println(it.next()); + } + } +}