添加元素到向量的末尾

Kev*_*ith 12 scala

Scaladocs解释了如何向Vector添加元素.

def :+(elem: A): Vector[A]
[use case] A copy of this vector with an element appended.
Run Code Online (Sandbox Code Playgroud)

例:

scala> Vector(1,2) :+ 3
res12: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

对于大型集合,复制整个Vector,然后向其添加元素似乎很昂贵.

将元素添加到Vector的最佳(最快)方法是什么?

Dav*_*ook 9

与不可变Vector的连接是O(logN).看看这篇论文,看看它是如何完成的.

http://infoscience.epfl.ch/record/169879/files/RMTrees.pdf


col*_*red 6

如果你要做很多追加,你应该使用一个队列,因为它保证了恒定的时间追加.有关集合的时间复杂性的信息,您可以参考此备忘单.

http://www.scala-lang.org/docu/files/collections-api/collections_40.html