将数组切片到 seq 没有副本
Slice array to seq with no copy
我正在尝试获取 Array
的一部分作为 Seq
避免复制。我可以使用 toSeq
方法。
val array = Array[AnyRef](
new Integer(1),
new Integer(2),
new Integer(3),
new Integer(4),
new Integer(5)
)
val seq = array.toSeq
array(1) = null
println(seq.mkString(",")) //1,null,3,4,5
工作正常:Ideone Live example。数组未被复制。但是当我尝试切片时
val array = Array[AnyRef](
new Integer(1),
new Integer(2),
new Integer(3),
new Integer(4),
new Integer(5)
)
val seq = array.toSeq.slice(0, 3)
array(1) = null
println(seq.mkString(",")) //1,2,3
可以看出复制已完成:Ideone Live Example。我试图避免它。有没有办法在 Scala 中做到这一点?
代码如下:
val a = (0 to 10).toArray
val b = a.toSeq.view.slice(1, 9)
a(5) = 12345
b.mkString(",") // res5: String = 1,2,3,4,12345,6,7,8
"Your scientists were so preoccupied with whether or not they could that they didn't stop to think if they should."
我正在尝试获取 Array
的一部分作为 Seq
避免复制。我可以使用 toSeq
方法。
val array = Array[AnyRef](
new Integer(1),
new Integer(2),
new Integer(3),
new Integer(4),
new Integer(5)
)
val seq = array.toSeq
array(1) = null
println(seq.mkString(",")) //1,null,3,4,5
工作正常:Ideone Live example。数组未被复制。但是当我尝试切片时
val array = Array[AnyRef](
new Integer(1),
new Integer(2),
new Integer(3),
new Integer(4),
new Integer(5)
)
val seq = array.toSeq.slice(0, 3)
array(1) = null
println(seq.mkString(",")) //1,2,3
可以看出复制已完成:Ideone Live Example。我试图避免它。有没有办法在 Scala 中做到这一点?
代码如下:
val a = (0 to 10).toArray
val b = a.toSeq.view.slice(1, 9)
a(5) = 12345
b.mkString(",") // res5: String = 1,2,3,4,12345,6,7,8
"Your scientists were so preoccupied with whether or not they could that they didn't stop to think if they should."