Closing a java.util.Iterator

前端 未结 7 1819
清酒与你
清酒与你 2020-12-29 02:32

I\'ve implemented a custom java.util.Iterator using a resource that should be released at the end using a close() method. That resource could

7条回答
  •  清酒与你
    2020-12-29 03:24

    Just define your own sub-interface of Iterator that includes a close method, and make sure you use that instead of the regular Iterator class. For example, create this interface:

    import java.io.Closeable;
    import java.util.Iterator;
    
    public interface CloseableIterator extends Iterator, Closeable {}
    

    And then an implementation might look like this:

    List someList = Arrays.asList( "what","ever" );
    final Iterator delegate = someList.iterator();
    return new CloseableIterator() {
        public void close() throws IOException {
            //Do something special here, where you have easy
            //access to the vars that created the iterator
        }
    
        public boolean hasNext() {
            return delegate.hasNext();
        }
    
        public String next() {
            return delegate.next();
        }
    
        public void remove() {
            delegate.remove();
        }
    };
    

提交回复
热议问题