2

I'm from a C# background where the iterators implement IDisposable interface. Are there any iterators in Java that implement a similar interface that makes them close automatically?

Maerlyn
  • 33,687
  • 18
  • 94
  • 85
batman
  • 4,728
  • 8
  • 39
  • 45

4 Answers4

7

Java's Iterator is just an abstraction for iterating over some collection of objects. If the underlying data structure needs some clean-up after iteration (e.g. closing a file), then you need to keep a reference to that underlying object so you can do whatever must be done to "dispose" of it.

DaoWen
  • 32,589
  • 6
  • 74
  • 101
4

In Java 7, you could create your own iterator (or a decorator for one) which also happens to implement AutoCloseable. You could then use it in a try block:

try ( Iterator<MyObject> it = new MyAutoCloseableIterator(list) ) {
    while (it.hasNext()) {
       MyObject obj = it.next();
    }
}

At the end of the try block, if the Iterator implements AutoCloseable interface, the ".close()" method will automagically be called on it.

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

I don't believe however that any of the built in iterators (which typically are inner classes to the collections, and thus not publicly available) implement this interface.

Another option would be to (again) code your own iterator, and close resources when the ".hasNext()" method return false.

Matt
  • 11,523
  • 2
  • 23
  • 33
1

In Java, Iterator is an interface itself. And it doesn't have any close() method.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
1

This is the API offered by an Iterator

Method Summary

boolean hasNext()
Returns true if the iteration has more elements. E next()
Returns the next element in the iteration. void remove()
Removes from the underlying collection the last element returned by the iterator (optional operation).

It was meant to replace Enumeration in the Java collections framework and is being used to iterate over a collection. It is based on the Iterator design pattern.
It's purpose is exactly what is offered. I.e. iteration. Has nothing to do with close etc.
If a class that implements the iterator interface e.g. Scanner offers a close this is part of the Scanner API. Unrelated to the iterator aspect/interface

Cratylus
  • 52,998
  • 69
  • 209
  • 339