Scala dynamic multidimensional mutable arrays such as data structures

Is there a way to build dynamic multidimensional arrays in Scala? I know that arrays in Scala should be initialized in their sizes and sizes, so I don't want this. The data structure must be dynamic. I tried to build it with lists in lists, but I lost myself somehow.

There are so many different types, maybe I just did not find the right one. So please push me in the right direction.

+7
types scala
source share
3 answers

If you want to do something like

a (5) = // result of some calculation

then you will need to use something from the hierarchy of mutable collections. I 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 allows you to automatically create and initialize up to 5D structures. Please also note that you can extend their length, but will not expand the entire multidimensional structure, only the one to which you add. 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)) 
+6
source share

Well, it depends a lot on what you intend to do with it, but your best guess is IndexedSeq[IndexedSeq[T]] (or deeper attachments), using Vector as the implementation for IndexedSeq (the default is the default).

For example:

scala> IndexedSeq (IndexedSeq (1, 2, 3), IndexedSeq (4, 5), IndexedSeq (6, 7, 8, 9)) res0: IndexedSeq [IndexedSeq [Int]] = Vector (Vector, 1, 2, 3 ), Vector (4, 5), Vector (6, 7, 8, 9))

+4
source share

You can create an array of two dims dynamically as follows:

 val aa : Array[Array[Int]] = Array.ofDim (3, 4) 

Ok, yes, I see the size is fixed. How about this:

 val i = random.nextInt (5) + 1 val j = new GregorianCalendar (). get (Calendar.DAY_OF_WEEK) val aa : Array[Array[Int]] = Array.ofDim (i, j) 

Yes, this is due to two dimensions. How would you use an array of a previously unknown dimension?

Good - at least you can:

 val aa : Array [Int] = Array.ofDim (2) 

aa: Array [Int] = Array (0, 0)

 val aaa = Array.fill (3) (aa) 

aaa: Array [Array [Int]] = Array (Array (0, 0), Array (0, 0), Array (0, 0))

+3
source share

All Articles