scala dynamic multi dimensional mutable arrays like datastructures

前端 未结 3 1583
长情又很酷
长情又很酷 2021-02-06 01:15

Is there any way to build dynamic multi-dimensional arrays in Scala? I know arrays in Scala must be initialized in its sizes and dimensions, so I don\'t want that. The data stru

3条回答
  •  既然无缘
    2021-02-06 01:20

    If you want to do something like

    a(5) = // result of some computation

    then you'll need to use something from the mutable collections hierarchy. I'd suggest ArrayBuffer.

    scala> import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable.ArrayBuffer
    
    scala> val a = ArrayBuffer.fill(3,3)(0)
    a: scala.collection.mutable.ArrayBuffer[scala.collection.mutable.ArrayBuffer[Int]] = ArrayBuffer(ArrayBuffer(0, 0, 0), ArrayBuffer(0, 0, 0), ArrayBuffer(0, 0, 0))
    
    scala> a(2)(1) = 4
    
    scala> a(0) = ArrayBuffer(1,2,3)
    
    scala> a
    res2: scala.collection.mutable.ArrayBuffer[scala.collection.mutable.ArrayBuffer[Int]] = ArrayBuffer(ArrayBuffer(1, 2, 3), ArrayBuffer(0, 0, 0), ArrayBuffer(0, 4, 0))
    

    Note that fill lets you automatically create and initialize up to 5D structures. Note also that you can extend the length of these, but it won't extend the entire multidimensional structure, just the one you add to. So, for example,

    scala> a(2) += 7 // Add one element to the end of the array
    res3: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 4, 0, 7)
    
    scala> a
    res4: scala.collection.mutable.ArrayBuffer[scala.collection.mutable.ArrayBuffer[Int]]
    = ArrayBuffer(ArrayBuffer(1, 2, 3), ArrayBuffer(0, 0, 0), ArrayBuffer(0, 4, 0, 7))
    

提交回复
热议问题