scala中的集合List

1.空集合

scala> Nil
res0: scala.collection.immutable.Nil.type = List()


scala> val l2=1::Nil
l2: List[Int] = List(1)

scala> val l3= 
     | 2::l2
l3: List[Int] = List(2, 1)

scala> val l4=1::2::3::Nil
l4: List[Int] = List(1, 2, 3)

2.定长集合

1.定义一个定长集合
scala> val l0 = List[Int](6)
l0: List[Int] = List(6)
scala> l0

res13: List[Int] = List(6)
scala> l0(0)
res14: Int = 6

scala> l0.length
res16: Int = 1

scala> l0(3)
java.lang.IndexOutOfBoundsException: 3
  at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:65)
  at scala.collection.immutable.List.apply(List.scala:84)
  ... 32 elided

scala> val 18 = new List[Int](4)
<console>:12: error: class List is abstract; cannot be instantiated
       val 18 = new List[Int](4)
                ^

  
说明:上面定义的是一个集合,数值为6,Int类型,,,这里要与数组区别对待

-------------------------------------------------------------------------------------


2.定义一个定长集合
scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)

集合有头有尾
scala> l.head
res1: Int = 1

scala> l.tail
res2: List[Int] = List(2, 3, 4, 5)

3.变成集合

定义变长集合要先导入:import scala.collection.mutable.ListBuffer
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> val l5=ListBuffer[Int]()
l5: scala.collection.mutable.ListBuffer[Int] = ListBuffer()
加集合
scala> l5 +=2
res4: l5.type = ListBuffer(2)

scala> l5 +=(3,4,5)
res5: l5.type = ListBuffer(2, 3, 4, 5)

加一个集合要++
scala> l5 ++=List(6,7,8)
res6: l5.type = ListBuffer(2, 3, 4, 5, 6, 7, 8)

减集合
scala> l5 -=2
res7: l5.type = ListBuffer(3, 4, 5, 6, 7, 8)

scala> l5 -=3
res8: l5.type = ListBuffer(4, 5, 6, 7, 8)

scala> l5 -=(1,4)
res9: l5.type = ListBuffer(5, 6, 7, 8)

scala> l5 --=List(5,6,7,8)
res11: l5.type = ListBuffer()


判断一个集合是不是空
scala> l5.isEmpty
res12: Boolean = true

判断一个集合是不是Int类型
scala> l5.isInstanceOf[Int]
res21: Boolean = false


scala> l5.is
isDefinedAt   isEmpty   isInstanceOf   isTraversableAgain


scala> l5.to
to        toBuffer       toIterable   toList   toParArray   toSet      toString        toVector   
toArray   toIndexedSeq   toIterator   toMap    toSeq        toStream   toTraversable              



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值