# Scala数组介绍和用法

## 本文概述

Scala数组可以是通用的。这意味着, 你可以拥有一个Array [T], 其中T是类型参数或抽象类型。 Scala数组与Scala序列兼容-你可以在需要Seq [T]的地方传递Array [T]。它还支持所有序列操作。

1. 一维数组
2. 多维数组

## Scala一维数组

#### 一维数组的语法

``````var arrayName : Array[arrayType] = new Array[arrayType](arraySize);   or
var arrayName = new Array[arrayType](arraySize)  or
var arrayName : Array[arrayType] = new Array(arraySize);   or
var arrayName = Array(element1, element2 ... elementN)``````

## Scala数组示例：一维

``````class ArrayExample{
var arr = Array(1, 2, 3, 4, 5)     	// Creating single dimensional array
def show(){
for(a<-arr)               		 // Traversing array elements
println(a)
println("Third Element  = "+ arr(2))        // Accessing elements by using index
}
}

object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}``````

``````1
2
3
4
5
Third Element  = 3``````

## Scala示例2：一维

``````class ArrayExample{
var arr = new Array[Int](5)     	// Creating single dimensional array
def show(){
for(a<-arr){               		 // Traversing array elements
println(a)
}
println("Third Element before assignment = "+ arr(2))        // Accessing elements by using index
arr(2) = 10                                                			 // Assigning new element at 2 index
println("Third Element after assignment = "+ arr(2))
}
}

object MainObject{
def main(args:Array[String]){
var a = new ArrayExample()
a.show()
}
}``````

``````0
0
0
0
0
Third Element before assignment = 0
Third Element after assignment = 10``````

## Scala将数组传递给函数

``````class ArrayExample{
def show(arr:Array[Int]){
for(a<-arr)                // Traversing array elements
println(a)
println("Third Element = "+ arr(2))        // Accessing elements by using index
}
}

object MainObject{
def main(args:Array[String]){
var arr = Array(1, 2, 3, 4, 5, 6)    // creating single dimensional array
var a = new ArrayExample()
a.show(arr)                     // passing array as an argument in the function
}
}``````

``````1
2
3
4
5
6
Third Element = 3``````

## Scala数组示例：使用Foreach循环进行迭代

``````class ArrayExample{
var arr = Array(1, 2, 3, 4, 5)     	// Creating single dimensional array
arr.foreach((element:Int)=>println(element))       // Iterating by using foreach loop
}

object MainObject{
def main(args:Array[String]){
new ArrayExample()
}
}``````

``````1
2
3
4
5``````

• 回顶