scala学习之Array

数组分为两种:定长数组(Array) 变长数组(Arraybuffer) 

val nums=new Array[Int](10)
		val a=new Array[String](10)
		import scala.collection.mutable.ArrayBuffer
		val b=ArrayBuffer[Int]()
		b+=1    //+= 表示在尾端添加一个 
		b+=(1,2,3,5)   //res5: b.type = ArrayBuffer(1, 1, 2, 3, 5)
		b++=Array(8,13,21,5)     res6: b.type = ArrayBuffer(1, 1, 2, 3, 5, 8, 13, 21, 5)
		b.trimEnd(2)//删除最后两个
		b.insert(0,0)//数组下标为0插入0
		b.insert(2,7,8,9)  //在下标为2之前插入:7,8,9 
		b.remove(2)//删除下标为2
		b.remove(1,2)//从下标为1删除2个


		val c=Array(2,3,7,11)
		val result=for(elem <- c) yield 2*elem
		//结果:result: Array[Int] = Array(4, 6, 14, 22)

		val result=for(elem <- c if elem%2==0) yield 2*elem
		//结果:result: Array[Int] = Array(4)
		val result=c.filter(_%2==0).map(2*_)

		val c=Array(1,7,2,9).sum
		//c: Int = 19
		val c=Array(1,7,2,9).max
		//c: Int = 9
		val c=Array(1,7,2,9).sorted
		//c: Array[Int] = Array(1, 2, 7, 9)
		import scala.collection.mutable.ArrayBuffer
		val c=ArrayBuffer(1,7,2,9).sorted
		//c: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 7, 9)
		
		val c=Array(1,7,2,9)
		scala> scala.util.Sorting.quickSort(c)
		scala> c
		//res2: Array[Int] = Array(1, 2, 7, 9)
		val d=scala.util.Sorting.quickSort(c)
		//       d: Unit = ()
		scala> val d=c.mkString("and")
		//d: String = 1and2and7and9	
		scala> val d=c.mkString("<",",",">")
		//d: String = <1,2,7,9>
		scala> val d=c.mkString("<","?",">")
		//d: String = <1?2?7?9>

		val matrix=Array.ofDim[Double](3,4)
		//matrix: Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 0.0,0.0, 0.0), Array(0.0, 0.0, 0.0, 0.0))
		matrix(2)(1)=42
		scala> matrix
		//res4: Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 42.0, 0.0, 0.0))

		val triangle=new Array[Array[Int]](10)
		//triangle: Array[Array[Int]] = Array(null, null, null, null, null, null, null, null, null, null)
		for(i <- 0 until triangle.length)
			triangle(i)=new Array[Int](i+1)
		scala> triangle
		res6: Array[Array[Int]] = Array(Array(0), Array(0, 0), Array(0, 0, 0), Array(0,0, 0, 0), Array(0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0))



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值