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

后端 未结 9 1625
星月不相逢
星月不相逢 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:33

    public class DescendingIterableDequeAdapter implements Iterable {
        private Deque original;
    
        public DescendingIterableDequeAdapter(Deque original) {
            this.original = original;
        }
    
        public Iterator iterator() {
             return original.descendingIterator();
        }
    }
    

    And then

    for (T item : new DescendingIterableDequeAdapter(deque)) {
    
    }
    

    So, for each such case, you'd need a special adapter. I don't think it is theoretically possible to do what you want, because the facility has to know what iterator-returning methods exist, so that it can call them.

    As for your additional question - I believe because the for-each loop was actually meant to make things shorter for general-purpose scenarios. And calling an additional method makes the syntax more verbose. It could've supported both Iterable and Iterator, but what if the object passed implemented both? (would be odd, but still possible).

提交回复
热议问题