定长数组
val a = new Array[String](5) //类似java的String[]
a.length
a(1)="11"
val b = Array(1,2,3,4,5,6)
b.sum
b.mkString()
b.mkString(",")
b.mkString("<",",",">") // ==> <1,2,3,4,5,6>
可变数组
scala.collection.mutable.ArrayBuffer
val c = scala.collection.mutable.ArrayBuffer[Int]()
c += 1
c += (2,3)
c ++= Array(4,5)
c.insert(0,0)
c.toArray
List
val l = List(1,2,3,4,5)
l.head
l.tail
val l2 = 1 :: Nil
l2.isEmpty
l2.tail:_* // => 可以转化成可变参数: Int*
Set
无序,不可重复
- scala的set对象实例可以转化为java.util.set
val ints = scala.collection.mutable.Set[Int]()
//引入scala.collection.JavaConverters用于Scala与Java集合的互转
import scala.collection.JavaConverters._
ints.asJava // => java.util.set
Map
val a = Map("aa" -> 1)
val b = scala.collection.mutable.Map("aa" -> 2)
val c = scala.collection.mutable.HashMap[String,Int]()
b("aa") // 有可能会报错
b.get("aa") // => Some (Option[Int])
b.getOrElse("aa", 2)
b += ("bb" -> 3)
for((key,value) <- b) {
println(key)
}
for(key <- b.keySet) {
println(key)
}
for(value <- b.values) {
println(value)
}
Option | Some | None
val m = Map(1 -> 2)
m.get(2).isEmpty
println(m.get(1).get)
元组tuple
val a = (1,23,4,5,6)
a._1
for(i <- 0 until(a.productArity))
val (aa, bb, cc, dd) = Array(1,2,3,4)
网友评论