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

问题描述

假设我有一个迭代器:

val it = List("a","b","c").iterator

我想要一份副本;我的代码是:

I want a copy of it; my code is:

val it2 = it.toList.iterator

这是正确的,但似乎并不好。有没有其他API可以做到这一点?

It's correct, but seems not good. Is there any other API to do it?

推荐答案

警告:从Scala 2.9.0开始,至少,这个将原始迭代器留空。你可以 val ls = it.toList; val it1 = ls.iterator; val it2 = ls.iterator 获得两份副本。或者使用复制(也适用于非列表)。

Rex的答案在书中,但事实上你的原始解决方案是迄今为止最多的高效的scala.collection.immutable.List's。

Rex's answer is by the book, but in fact your original solution is by far the most efficient for scala.collection.immutable.List's.

列表迭代器可以使用该机制进行复制,基本上没有开销。这可以通过快速查看scala.collection.immutable.LinearSeq中的iterator()的实现来确认。 toList方法的定义,它简单地返回后备Seq的_.toList,如果它是List(就像你的情况那样)是标识。

List iterators can be duplicated using that mechanism with essentially no overhead. This can be confirmed by a quick review of the implementation of iterator() in scala.collection.immutable.LinearSeq, esp. the definition of the toList method, which simply returns the _.toList of the backing Seq which, if it's a List (as it is in your case) is the identity.

在调查你的问题之前我没有意识到List迭代器的这个属性,我非常感谢这些信息......除此之外,它意味着许多列表修改算法可以通过使用Scala不可变列表有效地实现迭代器作为鹅卵石。

I wasn't aware of this property of List iterators before investigating your question, and I'm very grateful for the information ... amongst other things it means that many "list pebbling" algorithms can be implemented efficiently over Scala immutable Lists using Iterators as the pebbles.

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

10-20 01:06