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

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)}
1
2
3

使用:: Nil 构造List

scala> var num=1::2::3::4::Nil
num: 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.isEmpty
res14: Boolean = false

//得到头
scala> n.head
res15: Int = 1
//的到尾
scala> n.last
res19: Int = 3
//得到去掉头的List
scala> n.tail
res16: List[Int] = List(2, 3)
//得到去掉尾的List
scala> n.init
res17: 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.reverse
res20: List[Int] = List(3, 2, 1)
//去掉前面n个
scala> n drop 1
res21: List[Int] = List(2, 3)
//得到前面n个
scala> f take 2
res22: List[String] = List(a, b)
// toArray
scala> f.toArray
res25: Array[String] = Array(a, b, c)

其他方法

//apply方法
scala>  List.apply(1, 2, 3)
res139: List[Int] = List(1, 2, 3)

//range方法,构建某一值范围内的List
scala>  List.range(2, 6)
res140: List[Int] = List(2, 3, 4, 5)

//步长为2
scala>  List.range(2, 6,2)
res141: List[Int] = List(2, 4)

//步长为-1
scala>  List.range(2, 6,-1)
res142: List[Int] = List()

scala>  List.range(6,2 ,-1)
res143: List[Int] = List(6, 5, 4, 3)

//构建相同元素的List
scala> List.make(5, "hey")
res144: List[String] = List(hey, hey, hey, hey, hey)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值