如何在Scala中复制迭代器? [英] How to copy iterator in Scala?

查看:139
本文介绍了如何在Scala中复制迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是如何克隆迭代器?

请不要盲目关闭此问题,在所谓的重复不要工作中给出的所有答案。 OP负责另一个问题,显然,答案符合HIS问题,但不符合我的。

Please do not blindly close this question, all the answers given in so-called duplicate DO NOT work. The OP is in charge of the other problem, and obviously, the answers fitted HIS problem, but not mine.

并非每个类似的问题都是重复的,有这样的功能作为SE上的扩展问题,唯一的方法是再次询问同一主题,以获得不同的,有效的答案。

Not every similar question is a duplicate, there is such feature as "expansion question" on SE, the only way is to ask again on the same subject to get different, working, answers.

我有迭代器。我想复制(复制)它,所以我可以完全独立地继续原始和复制。

I have iterator. I would like to get copy (duplicate) of it, so then I could proceed with original and copy completely independently.

重要

通过反思或序列化进行复制是禁止的(性能损失)。

Copying through reflection or serialization is no-go (performance penalty).

示例

var list = List(1,2,3,4,5)
var it1 = list.iterator
it1.next()

var it2 = it1   // (*)
it2.next()

println(it1.next())

这只会引用 it1 ,所以在更改 it1时 it2 也会发生变化,反之亦然。

This would make simply reference to it1, so when changing it1, it2 changes as well and vice-versa.

以上示例使用列表,我目前正在努力解决 HashMap ,但问题是一般问题 - 只是迭代器。

The example above uses List, I am currently struggling with HashMap, but the question is general one -- just iterator.

如果你编辑行(*)并写:

If you edit line (*) and write:

var it2 = it1.toList.iterator

(这被建议作为链接问题的解决方案)执行程序时抛出异常。

(this was suggested as solution in the linked question) the exception is thrown while executing the program.

你拿这份清单......。不,我没有。我没有列表,我有迭代器。一般来说,我不知道任何关于迭代器的基础的集合,我唯一拥有的是迭代器。我必须分叉它。

"You take the list and...". No, I don't. I don't have a list, I have iterator. In general I don't know anything about collection which underlies the iterator, the only thing I have is iterator. I have to "fork" it.

推荐答案

你不能在不破坏它的情况下复制迭代器。 iterator 的合约是它只能遍历一次。

You can't duplicate an iterator without destroying it. The contract for iterator is that it can only be traversed once.

你链接的问题显示了如何获得两份副本换取你销毁的那份。您不能继续使用原件,但现在可以独立向前运行两个新副本。

The question you linked to shows how to get two copies in exchange for the one you've destroyed. You cannot keep using the original, but you can now run the two new copies forward independently.

这篇关于如何在Scala中复制迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆