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?
-
Which iterators implement `IDisposable`? Can you give an example? – Dan Puzey Aug 20 '12 at 10:43
-
@DanPuzey - IEnumerator
implements IDisposable – manojlds Aug 20 '12 at 10:48 -
How lame on behalf of java is this! – Mike Nakis May 01 '15 at 07:37
-
[I had wished for Java Streams to be more like this](https://stackoverflow.com/q/34753078/521799). Unfortunately, they aren't. – Lukas Eder Jun 05 '17 at 08:35
4 Answers
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.
- 32,589
- 6
- 74
- 101
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.
- 11,523
- 2
- 23
- 33
In Java, Iterator is an interface itself. And it doesn't have any close() method.
- 14,972
- 14
- 61
- 108
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
- 52,998
- 69
- 209
- 339