Scala 二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15754688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:08:01  来源:igfitidea点击:

scala 2 dimensional array

scalamultidimensional-array

提问by Wins

This may sound easy, but I just can't get it right.

这听起来可能很简单,但我就是做对了。

How to create a 2 dimensional array with size 100 by 60 in Scala? Supposed I have class called Abcd and I want to create a 2 dimensional array of Abcd. I tried with the following code but doesn't work.

如何在 Scala 中创建大小为 100 x 60 的二维数组?假设我有一个名为 Abcd 的类,我想创建一个 Abcd 的二维数组。我尝试使用以下代码但不起作用。

var myArray = new Array[Array[Abcd]](100,60)

It complains "too many arguments for constructor Array"

它抱怨“构造函数数组的参数太多”

回答by Alex Yarmula

The currently recommended way is to use ofDim:

目前推荐的方法是使用ofDim

var myArray = Array.ofDim[Abcd](100, 60)

回答by Chick

Or if you prefer to have your array start with ABCD's instead of nulls

或者,如果您希望数组以 ABCD 而不是空值开头

Array.fill[ABCD](100,6) { new ABCD }

or if the ABCD vary in some regular way by position

或者如果 ABCD 因位置而有规律地变化

Array.tabulate[ABCD](100,6) { (i,j) => new ABCD(i,j) }

回答by Johan S

I know this question is answered but one problem I ran into was that @alexwriteshere's solution and @Chick's solution was only good if you wanted a matrix.

我知道这个问题已得到解答,但我遇到的一个问题是 @alexwriteshere 的解决方案和 @Chick 的解决方案仅在您需要矩阵时才有效。

To be able to create a two-dimensional array with (if viewed as first number of rows then number of columns), do something like this:

为了能够创建一个二维数组(如果被视为第一个行数然后是列数),请执行以下操作:

val array = Array.ofDim[Array[Char]](2)
array(0) = Array.ofDim[Char](10)
array(1) = Array.ofDim[Char](20)