Scala: 将元素附加到 Array 的最佳方法是什么?

假设我有一个 Array[Int]

val array = Array( 1, 2, 3 )

现在我想给数组添加一个元素,比如值 4,如下例所示:

val array2 = array + 4     // will not compile

I can of course use System.arraycopy() and do this on my own, but there must be a Scala library function for this, which I simply could not find. Thanks for any pointers!

备注:

  1. 我知道我可以附加另一个 Array 元素,如下面这行所示,但是这似乎太迂回了:

    val array2b = array ++ Array( 4 )     // this works
    
  2. I am aware of the advantages and drawbacks of List vs Array and here I am for various reasons specifically interested in extending an Array.

Edit 1

Thanks for the answers pointing to the :+ operator method. This is what I was looking for. Unfortunately, it is rather slower than a custom append() method implementation using arraycopy -- about two to three times slower. Looking at the implementation in SeqLike[], a builder is created, then the array is added to it, then the append is done via the builder, then the builder is rendered. Not a good implementation for arrays. I did a quick benchmark comparing the two methods, looking at the fastest time out of ten cycles. Doing 10 million repetitions of a single-item append to an 8-element array instance of some class Foo takes 3.1 sec with :+ and 1.7 sec with a simple append() method that uses System.arraycopy(); doing 10 million single-item append repetitions on 8-element arrays of Long takes 2.1 sec with :+ and 0.78 sec with the simple append() method. Wonder if this couldn't be fixed in the library with a custom implementation for Array?

Edit 2

For what it's worth, I filed a ticket: https://issues.scala-lang.org/browse/SI-5017

189334 次浏览

可以使用 :+将元素附加到数组中,使用 +:将元素附加到数组前面:

0 +: array :+ 4

应产生:

res3: Array[Int] = Array(0, 1, 2, 3, 4)

它与 Seq的任何其他实现相同。

val array2 = array :+ 4
//Array(1, 2, 3, 4)

作品也“反转”:

val array2 = 4 +: array
Array(4, 1, 2, 3)

还有一个“就地”版本:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

The easiest might be:

Array(1, 2, 3) :+ 4

实际上,Array 可以在 WrappedArray中隐式转换