本文介绍了循环迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要遍历一个List,但要循环遍历.我也需要向列表中添加新元素并遍历所有元素(旧元素和新闻元素),我该怎么做?有没有适合他们的数据结构?
I need iterate through a List but circular way. I need too add new elements to the list and iterate over all elements (olds and news elements), How I do it? Is there any data structure for them?
推荐答案
我认为这可能就是您想要的;甚至在迭代过程中也可以向列表中添加新元素的功能.代码很丑陋,但似乎可以正常工作.
I think maybe this is what you want; the ability to add new elements to your list even as you are iterating it. The code is ugly but it seems to work.
import scala.collection.mutable.Queue
class Circular[A](list: Seq[A]) extends Iterator[A]{
val elements = new Queue[A] ++= list
var pos = 0
def next = {
if (pos == elements.length)
pos = 0
val value = elements(pos)
pos = pos + 1
value
}
def hasNext = !elements.isEmpty
def add(a: A): Unit = { elements += a }
override def toString = elements.toString
}
您可以像这样使用它:
scala> var circ = new Circular(List(1,2))
res26: Circular[Int] = Queue(1,2)
scala> circ.next
res27: Int = 1
scala> circ.next
res28: Int = 2
scala> circ.next
res29: Int = 1
scala> circ.add(5)
scala> circ.next
res30: Int = 2
scala> circ.next
res31: Int = 5
scala> circ
res32: Circular[Int] = Queue(1,2,5)
这篇关于循环迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!