斯卡拉:什么是一个元素追加到一个数组的最佳方式?
说我有一个数组[INT]
像
val array = Array( 1, 2, 3 )
现在我想将一个元素追加到数组,说值 4
,如下面的例子:
Now I would like to append an element to the array, say the value 4
, as in the following example:
val array2 = array + 4 // will not compile
我当然可以使用的System.arraycopy()
键,这样做我自己,但必须有这样的Scala库函数,我根本找不到。感谢您的指点!
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!
注:
-
我知道我可以追加要素的另一个数组,就像下面的行,但似乎过于迂回的:
I am aware that I can append another Array of elements, like in the following line, but that seems too round-about:
val array2b = array ++ Array( 4 ) // this works
我知道的优点和列表VS阵列的缺点,在这里我以各种理由在延伸的阵列特别感兴趣。
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.
感谢指向的答案:+
运算符方法。这就是我一直在寻找。不幸的是,它是而不是使用 arraycopy
定制append()方法执行慢 - 大约2至3倍慢。综观 SeqLike []
的实施,将创建一个生成器,然后将阵列添加到它,然后追加通过建造完成,那么生成器渲染。不是一个很好的实施阵列。我做了一个快速基准比较两种方法,寻找最快的时间十个周期。做一个单项10万元重复附加到某些类富
的8元数组实例需要3.1秒, +
和1.7秒,一个简单的追加()
使用方法 System.arraycopy();
做千万单项追加长的8单元阵列重复需要2.1秒, +
和0.78秒,简单的追加()
方法。不知道这不可能固定在一个自定义实现库阵列
?
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
?
有关它的价值,我提起了票:
https://issues.scala-lang.org/browse/SI-5017
For what it's worth, I filed a ticket: https://issues.scala-lang.org/browse/SI-5017
您可以使用 +
来追加元素阵列和 +
来prePEND是:
You can use :+
to append element to array and +:
to prepend it:
0 +: array :+ 4
应该产生:
res3: Array[Int] = Array(0, 1, 2, 3, 4)
这是相同与任何其他的Scala集合。
It's the same as with any other Scala collection.