Idiomatic way to use for-each loop given an iterator?

后端 未结 9 1606
星月不相逢
星月不相逢 2020-12-03 09:52

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 : /*         


        
9条回答
  •  执笔经年
    2020-12-03 10:22

    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.

提交回复
热议问题