Scala 动态多维可变数组,如数据结构 [英] scala dynamic multi dimensional mutable arrays like datastructures

查看:41
本文介绍了Scala 动态多维可变数组,如数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Scala 中构建动态多维数组?我知道 Scala 中的数组必须以其大小和维度进行初始化,所以我不想要那样.数据结构应该是动态的.我试图用列表中的列表来构建它,但我以某种方式迷失了自己.

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 structure should be dynamic. I tried to build it with lists in lists, but I lost myself some way.

有很多不同的类型,也许我只是没有找到合适的.所以请把我推向正确的方向.

There are so many different types, maybe I just didn't find the right one. So please push me to the right direction.

推荐答案

如果你想做类似的事情

a(5) =//一些计算的结果

a(5) = // result of some computation

那么你需要使用可变集合层次结构中的一些东西.我建议 ArrayBuffer.

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))

请注意,fill 可让您自动创建和初始化最多 5D 结构.另请注意,您可以扩展这些的长度,但它不会扩展整个多维结构,只会扩展您添加的多维结构.因此,例如,

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))

这篇关于Scala 动态多维可变数组,如数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆