A DESCRIPTION OF THE REQUEST :
Guarantee that if iterator class implements java.io.Closeable (or some newly introduced interface), close() will be called after termination of iteration, regardless of whether we terminate normally or through exception.
JUSTIFICATION :
With the advent of enhanced for loop, one could write code like:
for (String line : new IterableFile("foo.txt")) {
// process line
}
The problem is that, care must be taken in the implementation of Iterator to close the file immediately upon any exception. Moreover, it is impossible to close the file properly if the processing block of the for loop throws an exception.
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
for (Type t : iterable) {
...
}
should be equal to
Iterator<T> it = iterable.iterator();
try {
while (it.hasNext()) {
Type t = it.next();
....
}
} finally {
if (it instanceof Closeable) {
((Closeable) it).close();
}
}
###@###.### 10/14/04 19:11 GMT