Is it true that the Java Iterator only supports moving in one direction? If so, what were the reasons for such a move through collections in Java ?

  • The main purpose of iterators is not to move around the collection, but to iterate over the elements of the collection. The iterator in java, in my opinion, is so much too verbose - the remove method seems superfluous, as if it had been crammed from another interface - vp_arth

2 answers 2

There is an Iterator , it is unidirectional and has methods next() and hasNext() , but there is a ListIterator , it is bidirectional, it has both next() and hasNext() , and previous() and hasPrevious() . What implementation to take in which case is the programmer's task. Regarding which collection of which iterator is used in already implemented collections, it is a question of the collection implementation itself.

    And what does not suit you? Yes, Iterator is an interface that allows you to "move" only in one direction - the direction depends on the implementation / implementation of the interface in a particular collection - you can make your own implementation.

    If you are not at all happy to write your own interface, like:

     public interface DoubleDirectionIterator<E> extends Iterator<E> { public boolean hasPrev(); public E prev(); }