标签:
Array定长数组,访问数组元素需要通过()
val nums = new Array[Int](10) //长度为10的int数组 初始化为0 val strs = new Array[String](10) //长度为10的String数组 初始化为null val s = Array("Hello", "World") //初始化数组长度为2,不需要new s(0) = "GoodBye" //访问数组元素通过() println(nums(0)) println(strs(0)) println(s(0)+" "+s(1))
结果
0 null GoodBye World
变长数组使用ArrayBuffer
import scala.collection.mutable.ArrayBuffer val 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) //数组转化成数组缓冲
结果
1
ArrayBuffer(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 步长为2 println() for(i<- (0 until b.length).reverse) print(b(i)) //反转 println() for(i<- b) print(i) //不使用数组下标直接访问元素 println()
结果
12345
135
54321
12345
通过for yield对数据进行转换
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.quickSort val 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())
结果
34 11 ArrayBuffer(2, 5, 7, 9, 11) 2 and 5 and 7 and 9 and 11 <2 and 5 and 7 and 9 and 11> [I@28acaa28 ArrayBuffer(2, 5, 7, 9, 11)
参考《快学Scala》
标签:
原文地址:http://www.cnblogs.com/one--way/p/5797813.html