数组 1 2 3 4 5 (1)定长数组定义格式: val arr=new Array[T](数组长度) (2)变长数组定义格式: val arr = ArrayBuffer[T]()
注意需要导包:import scala.collection.mutable.ArrayBuffer
例程 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 object ArrayApp { def main (args: Array [String ]): Unit = { val arr = new Array [String ](5 ) arr(1 ) = "HAHA" println(arr.mkString("," )) println("**********************************************************" ) val arr2 = Array ("Hello" , "Scala" , "Hadoop" , "Spark" , "Storm" ) for (elem <- arr2) { println(elem) } println("**********************************************************" ) for (elem <- arr2.reverse) { println(elem) } println("**********************************************************" ) var arr3 = scala.collection.mutable.ArrayBuffer [String ]() arr3.++=(arr2) arr3 += "你好" println(arr3.mkString("," )) println("**********************************************************" ) arr3.remove(2 ) println(arr3.mkString("," )) println("**********************************************************" ) arr3.trimEnd(4 ) println(arr3.mkString("," )) } }
结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 null,HAHA,null,null,null ********************************************************** Hello Scala Hadoop Spark Storm ********************************************************** Storm Spark Hadoop Scala Hello ********************************************************** Hello,Scala,Hadoop,Spark,Storm,你好 ********************************************************** Hello,Scala,Spark,Storm,你好 ********************************************************** Hello
yield关键字将原始的数组进行转换会产生一个新的数组,原始的数组不变
1 2 3 4 5 6 7 8 9 10 11 12 val arr4 = Array (1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 )val res = for (e <- arr4 if e % 2 == 0 ) yield e * 10 println(res.mkString("," )) println("**********************************************************" ) val resPlus = arr4.filter(_ % 2 == 0 ).map(_ * 10 )println(resPlus.mkString("," ))
结果
1 2 3 20,40,60,80 ********************************************************** 20,40,60,80
数组常用算法 1 2 3 4 5 6 7 8 9 10 val arr5 = Array (7 , 8 , 9 , 1 , 2 , 3 , 4 , -5 , 6 )println(arr5.sum) println(arr5.max) println(arr5.min) println(arr5.sorted.mkString("," ))
结果
1 2 3 4 35 9 -5 -5,1,2,3,4,6,7,8,9