ARM Blocks: ease of use and for loops

Joshua Bloch jjb at google.com
Mon Nov 23 09:42:48 PST 2009


Howard,

I'm not sure if we want a Closeable-enabled version of a for-each loop in
Java.  I discussed this topic with the guy who added the using statement to
C# (Peter Hallam, now at Google), and he agreed that the Closeable for-each
hybrid didn't really mesh with Java.

         Josh

P.S.  Peter just loves the using statement in C#, and is enthusiastic about
ARM blocks in Java.

On Mon, Nov 23, 2009 at 5:14 AM, Howard Lovatt <howard.lovatt at iee.org>wrote:

> If you have interfaces I think you can add a Closeable version of a
> for-each
> loop; without the "RandomAccess hell", e.g.:
>
> interface SafeCloseable { void close(); }
>
> interface SafeCloseableIterator<E> extends Iterator<E>, SafeCloseable {}
>
> interface SafeCloseableIterable<E> extends Iterable<E>
> { SafeCloseableIterator safeCloseableIterator(); }
>
> class Source implements SafeCloseableIterable<String> {
>  public SafeCloseableIterator safeCloseableIterator() { return new
> SourceIterator(); }
>
>  public Iterator iterator() { return new SourceIterator(); }
> }
>
> class SourceIterator implements SafeCloseableIterator<String> {
>  private static final String[] out = { "Hello", "Hello", "World", "World"
> };
>
>  private int index = 0;
>
>  public boolean hasNext() { return ( index >= 0 ) && ( index < out.length
> ); }
>
>  public String next() { return out[ index++ ]; }
>
>  public void remove() { throw new UnsupportedOperationException( "Not
> supported." ); }
>
>  public void close() { index = -1; }
> }
>
> class FilterIterator implements SafeCloseableIterator<String> {
>  private final SafeCloseableIterator<String> source;
>
>  public FilterIterator( final Source source ) { this.source =
> source.safeCloseableIterator(); }
>
>  public boolean hasNext() {
>    if ( source.hasNext() ) { source.next(); }
>    return source.hasNext();
>  }
>
>  public String next() { return source.next(); }
>
>  public void remove() { source.remove(); }
>
>  public void close() { source.close(); }
> }
>
> class Filter implements SafeCloseableIterable<String> {
>  private final Source source;
>
>  public Filter( final Source source ) { this.source = source; }
>
>  public SafeCloseableIterator safeCloseableIterator() { return new
> FilterIterator( source ); }
>
>  public Iterator iterator() { return new FilterIterator( source ); }
> }
>
> public class Main {
>  public static void main( final String[] notUsed ) {
>    final Filter filter = new Filter( new Source() );
>    for ( final String s : filter ) { System.out.println( s ); }
>    final SafeCloseableIterator<String> i = filter.safeCloseableIterator();
>    try {
>      while ( i.hasNext() ) {
>        final String s = i.next();
>        System.out.println( s );
>      }
>    } finally { i.close(); }
>  }
> }
>
>



More information about the coin-dev mailing list