scala:数组




定义一个长度不变的整型数组:

val a = new Array[int](10) 
//Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

定义有初值的数组,不用new

val s = Array("a", "b") 
//长度为2的Array[String],通过初值确定类型

取用数组里面的值用(),而不是用[]println(s(0))

定义可变长度数组

import scala.collection.mutable.ArrayBuffer

scala> val b = ArrayBuffer[Int]()
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> b += 1
res107: b.type = ArrayBuffer(1)

scala> b += (1,2)
res108: b.type = ArrayBuffer(1, 1, 2)

scala> b ++= Array(3, 8)
res109: b.type = ArrayBuffer(1, 1, 2, 3, 8)

scala> b.toArray
res112: Array[Int] = Array(1, 1, 2, 3, 8)


scala> res112.toBuffer
res113: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 1, 2, 3, 8)

数组运算

不会改变原数组,适用于ArrayBuffer

Array(1,2,3).sum
Array(1,2,3).max
Array(1,2,3).min
Array(3,2,3).sorted

quickSort会重新排列原数组,但不适用于ArrayBuffer

scala> val arr = Array(2,3,2)
arr: Array[Int] = Array(2, 3, 2)

scala> scala.util.Sorting.quickSort(arr)

scala> arr
res14: Array[Int] = Array(2, 2, 3)
posted @ 2018-12-29 08:59  xuejianbest  阅读(174)  评论(0编辑  收藏  举报