31 篇文章 0 订阅

# Scala 数组

Scala 语言中提供的数组是用来存储固定大小的同类型元素，数组对于每一门编辑应语言来说都是重要的数据结构之一。

## 声明数组

var z:Array[String] = new Array[String](3)

var z = new Array[String](3)

z(0) = "Runoob"; z(1) = "Baidu"; z(4/2) = "Google"

var z = Array("Runoob", "Baidu", "Google")

## 处理数组

object Test {
def main(args: Array[String]) {
var myList = Array(1.9, 2.9, 3.4, 3.5)

// 输出所有数组元素
for ( x <- myList ) {
println( x )
}

// 计算数组所有元素的总和
var total = 0.0;
for ( i <- 0 to (myList.length - 1)) {
total += myList(i);
}
println("总和为 " + total);

// 查找数组中的最大元素
var max = myList(0);
for ( i <- 1 to (myList.length - 1) ) {
if (myList(i) > max) max = myList(i);
}
println("最大值为 " + max);

}
}

$scalac Test.scala$ scala Test
1.9
2.9
3.4
3.5

## 多维数组

var myMatrix = ofDim[Int](3,3)

import Array._

object Test {
def main(args: Array[String]) {
var myMatrix = ofDim[Int](3,3)

// 创建矩阵
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
myMatrix(i)(j) = j;
}
}

// 打印二维阵列
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
print(" " + myMatrix(i)(j));
}
println();
}

}
}

$scalac Test.scala$ scala Test
0 1 2
0 1 2
0 1 2

## 合并数组

import Array._

object Test {
def main(args: Array[String]) {
var myList1 = Array(1.9, 2.9, 3.4, 3.5)
var myList2 = Array(8.9, 7.9, 0.4, 1.5)

var myList3 =  concat( myList1, myList2)

// 输出所有数组元素
for ( x <- myList3 ) {
println( x )
}
}
}

$scalac Test.scala$ scala Test
1.9
2.9
3.4
3.5
8.9
7.9
0.4
1.5

## 创建区间数组

import Array._

object Test {
def main(args: Array[String]) {
var myList1 = range(10, 20, 2)
var myList2 = range(10,20)

// 输出所有数组元素
for ( x <- myList1 ) {
print( " " + x )
}
println()
for ( x <- myList2 ) {
print( " " + x )
}
}
}

$scalac Test.scala$ scala Test
10 12 14 16 18
10 11 12 13 14 15 16 17 18 19

## Scala 数组方法

1

def apply( x: T, xs: T* ): Array[T]

2

def concat[T]( xss: Array[T]* ): Array[T]

3

def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit

4

def empty[T]: Array[T]

5

def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]

scala> Array.iterate(0,3)(a=>a+1)
res1: Array[Int] = Array(0, 1, 2)
6

def fill[T]( n: Int )(elem: => T): Array[T]

7

def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]

8

def ofDim[T]( n1: Int ): Array[T]

9

def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]

10

def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]

11

def range( start: Int, end: Int, step: Int ): Array[Int]

12

def range( start: Int, end: Int ): Array[Int]

13

def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]

scala> Array.tabulate(3)(a => a + 5)
res0: Array[Int] = Array(5, 6, 7)
14

def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]

• 0
点赞
• 0
收藏
• 打赏
• 0
评论
01-25 2178
04-01 118
06-17 3192
01-15 2040
07-09 2846
04-20 4089
03-16 1729
03-16 3808
12-01 6万+

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

lucasmaluping

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。