How to efficient copy an Array to another in Scala?

前端 未结 4 1507
轻奢々
轻奢々 2021-01-12 03:28

How I can use another way to copy a Array to another Array?

My thought is to use the = operator. For example:

         


        
4条回答
  •  萌比男神i
    2021-01-12 03:56

    Another option is to create the new array, B, using A as a variable argument sequence:

    val B = Array(A: _*)
    

    The important thing to note is that using the equal operator, C = A, results in C pointing to the original array, A. That means changing C will change A:

    scala> val A = Array(1, 2, 3, 4)
    A: Array[Int] = Array(1, 2, 3, 4)
    
    scala> val B = Array(A: _*)
    B: Array[Int] = Array(1, 2, 3, 4)
    
    scala> val C = A
    C: Array[Int] = Array(1, 2, 3, 4)
    
    scala> B(0) = 9
    
    scala> A
    res1: Array[Int] = Array(1, 2, 3, 4)
    
    scala> B
    res2: Array[Int] = Array(9, 2, 3, 4)
    
    scala> C(0) = 8
    
    scala> C
    res4: Array[Int] = Array(8, 2, 3, 4)
    
    scala> A
    res5: Array[Int] = Array(8, 2, 3, 4)
    

提交回复
热议问题