Java中有可写的迭代器吗?
在 C+ 中,可以使用迭代器写入序列。最简单的例子是:
vector<int> v;
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
*it = 42;
}
我需要更复杂的东西 - 将迭代器保留为类成员以供以后使用。 但我不知道如何从 Java 迭代器获得这种行为。
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ListIterator
(您可以通过 < 获取代码>List#listIterator())有add()
和set()
方法允许您分别在当前迭代索引处插入和替换项目。这是我能想到的 Java 中唯一的“可写迭代器”。但不确定这是否是给定 C++ 代码的精确替换,因为我不懂 C++。
The
ListIterator
(which you can obtain byList#listIterator()
) hasadd()
andset()
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++.
由于可以通过索引直接快速地访问数组,因此您实际上并不需要迭代器对象。将数组的索引保存在该类成员中还不够吗?这将允许读取和写入数组的值。
PS:您可以使用 ArrayList,它是一组自动增长的数组,并使用 Balus 所描述的 ListIterator 来使用迭代器对象方法。
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.
看起来更像是您想要一个
List
(或者可能是其他一些集合,例如Set
)或数组。另外,您可以使内容可变。对于整数来说它看起来很愚蠢,但继续你的例子
Looks more like you want a
List
(or maybe some other collection, likeSet
) or an array.Also, you could just make your contents mutable. It looks silly for integers, but continuing your example