下面是Iterator
的{{1}}方法的代码:
++
在评论中,它说:/** Concatenates this iterator with another.
*
* @param that the other iterator
* @return a new iterator that first yields the values produced by this
* iterator followed by the values produced by iterator `that`.
* @note Reuse: $consumesTwoAndProducesOneIterator
* @usecase def ++(that: => Iterator[A]): Iterator[A]
*/
def ++[B >: A](that: => GenTraversableOnce[B]): Iterator[B] = new Iterator[B] {
// optimize a little bit to prevent n log n behavior.
private var cur : Iterator[B] = self
// since that is by-name, make sure it's only referenced once -
// if "val it = that" is inside the block, then hasNext on an empty
// iterator will continually reevaluate it. (ticket #3269)
lazy val it = that.toIterator
// the eq check is to avoid an infinite loop on "x ++ x"
def hasNext = cur.hasNext || ((cur eq self) && {
it.hasNext && {
cur = it
true
}
})
def next() = { hasNext; cur.next() }
}
。
何时以及如何连接两个迭代器导致n log n?
答案 0 :(得分:2)
根据大众需求,我回答了我自己的问题,引用了上面的@Paolo Falabella评论:
在“Scala 2nd ed编程”中提到过。 log n是由于 通过必须在每个步骤决定引入的额外间接 如果下一个元素来自第一个或第二个,则迭代 迭代器。