Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a writable iterator in Java?

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

vector<int> v;
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
    *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?

like image 914
Łukasz Lew Avatar asked May 10 '10 12:05

Łukasz Lew


2 Answers

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++.

like image 87
BalusC Avatar answered Sep 19 '22 15:09

BalusC


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.

like image 31
Simon Avatar answered Sep 19 '22 15:09

Simon