第九节:List-以及常规用法

来源:互联网 发布:淘宝网店如何起步 编辑:程序博客网 时间:2024/06/02 07:11

List 的值不能被改变

生成List

scala> var f=List("a","b","c")f: List[String] = List(a, b, c)scala> var n=List(1,2,3)n: List[Int] = List(1, 2, 3)

遍历

scala> for(i<-n){println(i)}123

使用:: Nil 构造List

scala> var num=1::2::3::4::Nilnum: List[Int] = List(1, 2, 3, 4)scala> var num=1::(2::(3::(4::Nil)))num: List[Int] = List(1, 2, 3, 4)

List 操作

//判断为空scala> n.isEmptyres14: Boolean = false//得到头scala> n.headres15: Int = 1//的到尾scala> n.lastres19: Int = 3//得到去掉头的Listscala> n.tailres16: List[Int] = List(2, 3)//得到去掉尾的Listscala> n.initres17: List[Int] = List(1, 2)//拼接scala> List(1,2,3):::List(4,5,6)res18: List[Int] = List(1, 2, 3, 4, 5, 6)//倒叙scala> n.reverseres20: List[Int] = List(3, 2, 1)//去掉前面n个scala> n drop 1res21: List[Int] = List(2, 3)//得到前面n个scala> f take 2res22: List[String] = List(a, b)// toArrayscala> f.toArrayres25: Array[String] = Array(a, b, c)

其他方法

//apply方法scala>  List.apply(1, 2, 3)res139: List[Int] = List(1, 2, 3)//range方法,构建某一值范围内的Listscala>  List.range(2, 6)res140: List[Int] = List(2, 3, 4, 5)//步长为2scala>  List.range(2, 6,2)res141: List[Int] = List(2, 4)//步长为-1scala>  List.range(2, 6,-1)res142: List[Int] = List()scala>  List.range(6,2 ,-1)res143: List[Int] = List(6, 5, 4, 3)//构建相同元素的Listscala> List.make(5, "hey")res144: List[String] = List(hey, hey, hey, hey, hey)
0 0