Scala的集合
Scala集合的分类
- 所有Scala的集合包均在:scala.collection下面
- 分为:mutable (可变的)和 immutable(不可变的)
- scala.collection.mutable 和 scala.collection.immutable
- **需要常掌握的:List,Array,Set,Tuple,Map,
- List item
Nil(空的List())**
官方文档:
https://docs.scala-lang.org/overviews/scala-book/collections-101.html
https://docs.scala-lang.org/overviews/collections-2.13/overview.html
也可参看其他网站:
https://www.runoob.com/scala/scala-lists.html
Array
- 常用API运算符如下:
scala> var arr = new Array[String](5)
arr: Array[String] = Array(null, null, null, null, null)
scala> arr(1)="Scala" // 下标从0开始
scala> arr
res2: Array[String] = Array(null, Scala, null, null, null)
scala> var array = new Array(3) // 不定义类型,就默认为Nothing类型
array: Array[Nothing] = Array(null, null, null)
scala> val a = Array(1,2,3,4,5,6)
a: Array[Int] = Array(1, 2, 3, 4, 5, 6)
scala> a.max
res3: Int = 6
scala> a.min
res4: Int = 1
scala> a.sum
res5: Int = 21
scala> for(ele <- a){
| println(ele)}
1
2
3
4
5
6
scala> a.mkString // 合并成String类型
res8: String = 123456
scala> a.mkString("[","+","]") // 带符号,合并成String类型
res9: String = [1+2+3+4+5+6]
scala> a
res10: Array[Int] = Array(1, 2, 3, 4, 5, 6)
scala> a.toString
res11: String = [I@35c69e6b
scala> a.toBuffer // 转换成可变集合
res13: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6)
ArrayBuffer(了解即可)
- 常用API运算符如下(了解即可,API可以看到源码或者官方文档):
- import scala.collection.mutable.ArrayBuffer
scala> import scala.collection.mutable.ArrayBuffer // 在IDEA中写代码,可以忽略这一步,会自动引入
import scala.collection.mutable.ArrayBuffer
scala> val b = ArrayBuffer[Int]() // 定义一个ArrayBuffer集合
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> b += 1
res14: b.type = ArrayBuffer(1)
scala> b += (2,3,4) // 批量添加元素
res15: b.type = ArrayBuffer(1, 2, 3, 4)
scala> b ++= Array(5,6,7) // 添加Array,使用两个+号。了解即可。
res16: b.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7)
scala> b.insert(0,20) // 指定位置0添加数值:20
scala> b
res18: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(20, 1, 2, 3, 4, 5, 6, 7)
scala> b.remove(2) // 下标2的数字被删除(第3个元素)
res19: Int = 2
scala> b
res20: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(20, 1, 3, 4,