Java中有可写的迭代器吗?

发布于 2024-08-31 13:37:35 字数 274 浏览 6 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

厌倦 2024-09-07 13:37:35

ListIterator (您可以通过 < 获取代码>List#listIterator())有add()set() 方法允许您分别在当前迭代索引处插入和替换项目。这是我能想到的 Java 中唯一的“可写迭代器”。

但不确定这是否是给定 C++ 代码的精确替换,因为我不懂 C++。

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

掌心的温暖 2024-09-07 13:37:35

由于可以通过索引直接快速地访问数组,因此您实际上并不需要迭代器对象。将数组的索引保存在该类成员中还不够吗?这将允许读取和写入数组的值。

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.

も让我眼熟你 2024-09-07 13:37:35

看起来更像是您想要一个 List (或者可能是其他一些集合,例如 Set)或数组。

另外,您可以使内容可变。对于整数来说它看起来很愚蠢,但继续你的例子

for (MutableInteger i : CollectionOfMInts) i.setTo(42);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文