# Scala--数组相关操作

## 一、定长数组

Array定长数组，访问数组元素需要通过()

`val nums = new Array[Int](10) //长度为10的int数组 初始化为0val strs = new Array[String](10) //长度为10的String数组 初始化为nullval s = Array("Hello", "World") //初始化数组长度为2，不需要news(0) = "GoodBye" //访问数组元素通过()println(nums(0))println(strs(0))println(s(0)+" "+s(1))`

`0nullGoodBye World`

## 二、变长数组

`import scala.collection.mutable.ArrayBufferval b = ArrayBuffer[Int]()b+=1//在尾端添加元素//ArrayBuffer(1)b+=(2,3,4,5)//在尾端添加多个元素//ArrayBuffer(1,2,3,4,5)b++=ArrayBuffer(8,19,20)//可以使用++-操作符追加任意集合//ArrayBuffer(1,2,3,4,5,8,19,20)b.trimEnd(3)//在尾部删除3个元素//ArrayBuffer(1,2,3,4,5)b.insert(2,6)//在下标2之前插入6//ArrayBuffer(1,2,6,3,4,5)b.insert(3,7,8,9)//在下标3之前插入7,8,9//ArrayBuffer(1,2,6,7,8,9,3,4,5)b.remove(2)//删除下标为2的元素//ArrayBuffer(1,2,7,8,9,3,4,5)b.remove(2,3)//从下标为2的元素开始，删除3个元素//ArrayBuffer(1,2,3,4,5)val c = b.toArray //不知道元素个数先构建ArrayBuffer，然后再转化成数组println(c(0))println(c.toBuffer) //数组转化成数组缓冲`

`1ArrayBuffer(1, 2, 3, 4, 5)`

## 三、遍历数组和数组缓冲

`for(i<- 0 until b.length) print(c(i)) //直接通过下标访问数组，until 不包括上线println()for(i<- 0 until (b.length,2)) print(b(i)) //step = 2 步长为2println()for(i<- (0 until b.length).reverse) print(b(i)) //反转println()for(i<- b) print(i) //不使用数组下标直接访问元素println()`

12345  135  54321  12345

## 四、数组转换

`val a = Array(2,3,5,7,11)val b = for(i<- a if i%2 !=0) yield i * 2 //生成一个新的数组for(i<- b) print(i+" ")`

`6 10 14 22`

## 五、常用算法

`import scala.util.Sorting.quickSortval a = Array(2,9,5,7,11)println(a.sum)println(a.max)quickSort(a)println(a.toBuffer)println(a.mkString(" and "))println(a.mkString("<"," and ",">"))println(a.toString)println(a.toBuffer.toString()) `

`3411ArrayBuffer(2, 5, 7, 9, 11)2 and 5 and 7 and 9 and 11<2 and 5 and 7 and 9 and 11>[[email protected]ArrayBuffer(2, 5, 7, 9, 11)`