问题描述
这正常吗?
scala> val x = Iterator(List[String]("str"))
lol: Iterator[List[String]] = non-empty iterator
scala> x.size
res1: Int = 1
scala> x.size
res2: Int = 0
实际上我正在遇到其他奇怪的错误..可能是错误?
And actually I'm meeting other weird errors.. a possible bug?
推荐答案
不,这不是bug.这是正常现象.
No it's not a bug. It's the normal behavior.
迭代器是可变的东西.您可以将它们视为指针.每次您要求迭代器为您提供下一个元素时,它都会将其再移一个位置.
Iterators are mutable things. You can think of them as pointers. Each time you ask an iterator to give you the next element it points to it will move one position further.
当您要求它提供尺寸时,它将遍历它指向的序列中的每个元素,每次向右移动一个位置.如果没有更多元素可以遍历iterator.hasNext == false
,它将返回大小.但是到那时,它将耗尽所有要素.再次调用size
时,迭代器已经位于末尾,因此它将立即返回0.
When you ask it to give you the size it will traverse each element in the sequence it points to, moving each time one position to the right. When it has no more elements to traverse iterator.hasNext == false
it will return the size. But by then it will have exhausted all the elements. When a new call to size
is made, the iterator is already positioned at the end, so it will immediately return 0.
要更好地了解正在发生的事情,可以执行以下操作:
To understand better what's happening, you can do this:
val it = Iterator(1, 2, 3, 4)
//it: >1 2 3 4
it.next() //ask for the next element
//it: 1 >2 3 4
it.next()
//it: 1 2 >3 4
println(it.size) // prints 2
//it: 1 2 3 4 >
println(it.size) // prints 0
这篇关于Scala 2.10中的错误是Iterator.size吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!