Scala 中的数组初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3881013/
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 02:28:53  来源:igfitidea点击:

Array initializing in Scala

scalaarray-initialization

提问by Emil

I'm new to Scala ,just started learning it today.I would like to know how to initialize an array in Scala.

我是 Scala 的新手,今天刚开始学习它。我想知道如何在 Scala 中初始化一个数组。

Example Java code

示例 Java 代码

String[] arr = { "Hello", "World" };

What is the equivalent of the above code in Scala ?

上面 Scala 代码的等价物是什么?

回答by Vasil Remeniuk

scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

回答by Martin Konicek

To initialize an array filled with zeros, you can use:

要初始化一个用零填充的数组,您可以使用:

> Array.fill[Byte](5)(0)
Array(0, 0, 0, 0, 0)

This is equivalent to Java's new byte[5].

这相当于 Java 的new byte[5].

回答by Dino Fancellu

Can also do more dynamic inits with fill, e.g.

也可以用填充做更多的动态初始化,例如

Array.fill(10){scala.util.Random.nextInt(5)} 

==>

==>

Array[Int] = Array(0, 1, 0, 0, 3, 2, 4, 1, 4, 3)

回答by Landei

Additional to Vasil's answer: If you have the values given as a Scala collection, you can write

Vasil 回答的补充:如果您将值作为 Scala 集合给出,则可以编写

val list = List(1,2,3,4,5)
val arr = Array[Int](list:_*)
println(arr.mkString)

But usually the toArray method is more handy:

但通常 toArray 方法更方便:

val list = List(1,2,3,4,5)
val arr = list.toArray
println(arr.mkString)

回答by Haimei

If you know Array's length but you don't know its content, you can use

如果您知道 Array 的长度但不知道其内容,则可以使用

val length = 5
val temp = Array.ofDim[String](length)

If you want to have two dimensions array but you don't know its content, you can use

如果你想拥有二维数组但你不知道它的内容,你可以使用

val row = 5
val column = 3
val temp = Array.ofDim[String](row, column)

Of course, you can change String to other type.

当然,您可以将 String 更改为其他类型。

If you already know its content, you can use

如果您已经知道其内容,则可以使用

val temp = Array("a", "b")

回答by akshat thakar

Another way of declaring multi-dimentional arrays:

另一种声明多维数组的方法:

Array.fill(4,3)("")

res3: Array[Array[String]] = Array(Array("", "", ""), Array("", "", ""),Array("", "", ""), Array("", "", ""))