When the enhanced for loop (foreach loop) was added to Java, it was made to work with a target of either an array or Iterable
.
for ( T item : /*
Rather than create a descendingIterator
, it would be better to write a descendingIterable()
method to return a descending iterable based on a deque- which basically takes the place of your anonymous class. That seems pretty reasonable to me. As per Colin's suggestion, the iterable implementation returned by this method would call descendingIterator
on the original deque each time its own iterator()
method was called.
If you've only got an iterator and want to keep it that way, you'd have to write an implementation of Iterable
which wrapped the iterator and returned it exactly once, throwing an exception if iterator()
is called more than once. That would work, but it would clearly be pretty ugly.