scala学习——(1)scala基础(下)

 (七)定长数组

  • val array_name = new Array[T](length)
  • val array_name = Array("","")
  • 通过()访问,而不是[]

 

scala> val a = new Array[Int](5)
a: Array[Int] = Array(0, 0, 0, 0, 0)

scala> val a = Array("Jack","Luncy")
a: Array[String] = Array(Jack, Luncy)
scala> a(1)
res10: String = Luncy

(八)变长数组

  • import scala.collection.mutable.ArrayBuffer
  • val buff = ArrayBuffer[T]()
  • +=/++=/insert/remove/toArray/sum/max/reverse
scala> val a = scala.collection.mutable.ArrayBuffer[Int]()
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> a += 1
res11: a.type = ArrayBuffer(1)

scala> a += 2
res12: a.type = ArrayBuffer(1, 2)

scala> a += (3,4,5)
res13: a.type = ArrayBuffer(1, 2, 3, 4, 5)

scala> a ++=Array(6,7,8)
res15: a.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)
scala> a.insert(0,0)

scala> a
res17: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 1, 2, 3, 4, 5, 6, 7, 8)

scala> a.remove(2)
res18: Int = 2

scala> a
res19: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 1, 3, 4, 5, 6, 7, 8)

scala> a.remove(0,1)

scala> a
res21: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 3, 4, 5, 6, 7, 8)
scala> a.toArray.sum
res23: Int = 34

scala> a.toArray.min
res24: Int = 1

scala> a.toArray.max
res25: Int = 8
scala> a.trimEnd(2)

scala> a
res27: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 3, 4, 5, 6)

(九)遍历数组

  • for(i <- 0 until array_name.length)
  • for(i<-array_name)
  • 事实上会更多的使用map、filter等等来操作
val b = Array(1,2,3,4,5,6,7,8)
    for (i <- 0 until b.length){
      println(i)
 val b = Array(1,2,3,4,5,6,7,8)
    for (elem <- b){
      println(elem)

Map(可变与不可变)

  • 不可变  val age = Map("Jack"->20,"Luncy"->"18")
  • 可变     val age = scala.collection.mutable.Map(...)
  • 初始化 val m = scala.collection.mutable.Map[String,Int]()

Map操作

  • 取值map(key),更好的方式map.getOrElse(key,default)
  • 更新map(key)=value /+=/-=
  • 迭代for((k,v)<-map){},也可以单独key或者value
  • for((k,-)<-map)/for((-,v)<-map){},也可以使用map.keySet或者map.values
    val age = Map("Jack"->20,"Luncy"->"18")
    for ((k,v) <- age){
      println("key is " + k +"value is "+v)
    }
  key is Jackvalue is 20
  key is Luncyvalue is 18

元组操作

  • ()里包含一系列的值
  • 通过._取值,下标从1开始。例如t._1
  • 迭代for(elem <- t.productlterator)
scala> val a  = (1,2,3,4)
a: (Int, Int, Int, Int) = (1,2,3,4)

scala> a._1
res41: Int = 1

 

参考资料:小象学院 陈超 仅供学习研究

posted on 2017-02-08 16:33  金秀  阅读(234)  评论(0编辑  收藏  举报

导航