scala数组相关操作
1.定长数组
object Test { def main(args: Array[String]): Unit = { //定长数组 val a = Array[Int](10) val s = Array("a","b") println(s(1)) } }
2.变长数组:数组缓冲
import scala.collection.mutable.ArrayBuffer object Test { def main(args: Array[String]): Unit = { //变长数组 java中的ArrayList scala中的ArrayBuffer val a = ArrayBuffer[Int]() //指定类型后操作 //添加单个元素 a += 1 a += 2 println(a) //ArrayBuffer(1,2) += 表示在末尾添加 //添加多个元素 a += (3, 4, 5) println(a) //ArrayBuffer(1, 2, 3, 4, 5) //与其他数组链接 a ++= Array(6, 7) println(a) //ArrayBuffer(1, 2, 3, 4, 5, 6, 7) //移除后面N个元素 a.trimEnd(3) println(a) //ArrayBuffer(1, 2, 3, 4) 从末尾添加和删除操作都是高效的 //指定位置添加、删除元素都是低效的,所有在那之后的元素都要平移 val b = ArrayBuffer[Int](1, 8) //插入单个元素 b.insert(1, 2) println(b) //ArrayBuffer(1, 2, 8) //插入多个元素 b.insert(2, 3, 4, 5) println(b) //ArrayBuffer(1, 2, 3, 4, 5, 8) //删除单个元素 println(b.remove(5)) //8 println(b)//ArrayBuffer(1, 2, 3, 4, 5) //删除多个 println(b.remove(2,3)) //()删除3个 println(b)//ArrayBuffer(1, 2) //无法确定数组个数时,先使用数组缓冲,在转为数组 val c = b.toArray // [I@742f1989 } }
3.遍历数组和数组缓冲
object Test { def main(args: Array[String]): Unit = { val arr = Array(1, 2, 3, 4, 5, 6) for (i <- 0 to arr.length - 1) { print(arr(i) + " ") } for (i <- 0 to(arr.length - 1, 2)) { //步长 print(arr(i) + " ") } for (i <- 0 until(arr.length, 2)) { print(arr(i) + " ") } for (a <- arr) { //类似java中的增强for循环 print(a + "-") } } }
4.数组转换
object Test { def main(args: Array[String]): Unit = { //数组转换 val arr = Array(1, 2, 3) val result = for (ele <- arr) yield ele * 2 //Array(2, 4, 6) //yield生成一个类型与原来类型相同的新的集合 //if守卫 val result2 = for (ele <- arr if ele % 2 != 0) yield ele * 2 //Array(2, 6) } }
import scala.collection.mutable.ArrayBuffer object Test { def main(args: Array[String]): Unit = { //数组转换 val arr = Array(2, 1, 3) println(arr.sum) //必须是数字类型 println(arr.min) println(arr.max) //排序 val a = arr.sorted for (ele <- a) { print(ele + " ") } //mkString toString val arrBuffer = ArrayBuffer(2, 1, 3) println(arr.mkString("and")) //2and1and3 println(arr) //[I@2c72dc45 println(arrBuffer.mkString("and")) //2and1and3 println(arrBuffer) //ArrayBuffer(2, 1, 3) } }