Take the 2-minute tour ×

In C+ one can use iterators for writing to a sequence. Simplest example would be:

vector<int> v;
    *it = 42;

I need something more complicated - keep iterator as a class member for a later use. But I don't know how to get this behavior from Java iterators.

Are there writable iterators in Java at all?
If not then what replaces them?

share|improve this question
add comment

3 Answers

up vote 7 down vote accepted

The ListIterator (which you can obtain by List#listIterator()) has add() and set() methods which allows you to respectively insert and replace the item at the currently iterated index. That's as far the only "writable iterator" as I can think of in Java.

Not sure though if that is the exact replacement of the given C++ code since I don't know C++.

share|improve this answer
Thanks. Is there anything like that for arrays ? –  Łukasz Lew May 10 '10 at 12:39
@Lukasz: You can turn an array into a List (in constant time) with Arrays.asList and then get a ListIterator from that. –  sepp2k May 10 '10 at 12:42
No, you should prefer List over array. The List is the Java abstraction of an array and you can use ArrayList to have a dynamically expandable array. To learn more about List (which is part of Java Collections API), check the Sun tutorial on the subject. –  BalusC May 10 '10 at 12:42
An ArrayList is a dynamically expansible array. A List could be anything (anything that adheres to the interface, that is). –  sepp2k May 10 '10 at 12:44
@sepp2k: corrected. –  BalusC May 10 '10 at 12:45
add comment

As arrays can be accessed directly and quickly by their index, you don't really need an iterator object. Wouldn't it be enought to save the index of the array in that class member? This would permit to read and write the value of the array.

PS: You could use an ArrayList, which is an automatically growing set of arrays and use the ListIterator as Balus described in order to use the iterator-object-approach.

share|improve this answer
To set a value int won't be enough. I need both int and array. –  Łukasz Lew May 10 '10 at 12:45
add comment

Looks more like you want a List (or maybe some other collection, like Set) or an array.

Also, you could just make your contents mutable. It looks silly for integers, but continuing your example

for (MutableInteger i : CollectionOfMInts) i.setTo(42);
share|improve this answer
add comment

Your Answer


