1 // defined array object 2 val arr0= new Array[String](10) 3 val arr1= Array("Hello","1") 4 println(arr1(0)) 5 arr1(0)="Hello Spark!" 6 println(arr1(0)) 7 // array's length can't change,but ArrayBuffer can. 8 9 val arr2= ArrayBuffer(1) 10 arr2+=1 11 for(item <- arr2) println(item) 12 arr2+=(2,3,4,5) 13 println(arr2.mkString(",")) 14 arr2++=Array(6,7,8) 15 println(arr2.mkString(",")) 16 arr2.trimEnd(5) 17 println(arr2.mkString(",")) 18 arr2.insert(2,6) 19 println(arr2.mkString(",")) 20 arr2.insert(2,5,5,6) 21 println(arr2.mkString(",")) 22 arr2.remove(5) 23 println(arr2.mkString(",")) 24 arr2.remove(1,4) 25 println(arr2.mkString(",")) 26 println(arr2.toArray.mkString(","))
输出结果:
Hello
Hello Spark!
1
1
1,1,2,3,4,5
1,1,2,3,4,5,6,7,8
1,1,2,3
1,1,6,2,3
1,1,5,5,6,6,2,3
1,1,5,5,6,2,3
1,2,3
1,2,3Process finished with exit code 0
1 val arr3=Array(1,2,3,4,5,6) 2 for(i<-0 until arr3.length) println(i+":"+arr3(i)) 3 for(elem<-arr3) println(elem) 4 5 val result= for(elem<-arr3) yield 2*elem; 6 println(result.mkString(",")) 7 var result0 = for(elem<-arr3 if elem%2==0) yield 2*elem; 8 println(result0.mkString(",")) 9 println(arr3.filter(_%2==0).map(2*_).mkString(",")) 10 11 println(arr3.sum) 12 val arr4= Array(5,3,10,1,3) 13 val result3= scala.util.Sorting.quickSort(arr4) 14 println(arr4.mkString("<",",",">")) 15 16 val arr5=ArrayBuffer(1,3,4,10,0,4,5) 17 println(arr5.sorted.mkString(",")) 18 19 val matrix= Array.ofDim[Double](3,4) 20 for(i<- 0 to 2;j<- 0 to 3) println("matrix("+i+")("+j+"):"+matrix(i)(j)) 21 matrix(1)(1)=23 22 for(i<- 0 to 2;j<- 0 to 3) println("matrix("+i+")("+j+"):"+matrix(i)(j)) 23 var triangle= new Array[Array[Int]](10) 24 for(i<-0 until(triangle.length)) triangle(i)= new Array[Int](i+1)
0:1
1:2
2:3
3:4
4:5
5:6
1
2
3
4
5
6
2,4,6,8,10,12
4,8,12
4,8,12
21
<1,3,3,5,10>
0,1,3,4,4,5,10
matrix(0)(0):0.0
matrix(0)(1):0.0
matrix(0)(2):0.0
matrix(0)(3):0.0
matrix(1)(0):0.0
matrix(1)(1):0.0
matrix(1)(2):0.0
matrix(1)(3):0.0
matrix(2)(0):0.0
matrix(2)(1):0.0
matrix(2)(2):0.0
matrix(2)(3):0.0
matrix(0)(0):0.0
matrix(0)(1):0.0
matrix(0)(2):0.0
matrix(0)(3):0.0
matrix(1)(0):0.0
matrix(1)(1):23.0
matrix(1)(2):0.0
matrix(1)(3):0.0
matrix(2)(0):0.0
matrix(2)(1):0.0
matrix(2)(2):0.0
matrix(2)(3):0.0Process finished with exit code 0