Article Directory
Set
Set (set) is not representative of repeating elements of the collection. Set has the following properties:
- Element does not repeat
- It does not guarantee insertion order
The scala also divided into two sets, one is immutable set, the other variable is set.
Set immutable
definition
grammar
//创建一个空的不可变集,语法格式
val/var 变量名 = Set[类型]()
//给定元素来创建一个不可变集,语法格式
val/var 变量名 = Set(元素1, 元素2, 元素3...)
The sample code
//定义一个空的不可变集
val a = Set[Int]()
//定义一个不可变集,保存以下元素:1,1,3,2,4,8
val a = Set(1,1,3,2,4,8)
Basic Operations
- Gets the size set
size
( )- Traversing the set
和遍历数组一致
( )- Adding an element to generate a the Set (
+
)- Splicing two sets, generates a the Set (
++
)- And stitching set list, generate a the Set (
++
)
The sample code
//1. 创建一个集,包含以下元素:1,1,2,3,4,5
val a = Set(1, 1, 2, 3, 4, 5)
//2. 获取集的大小
a.size
//3. 遍历集,打印每个元素 (set集是乱序的)
for (i <- a) println(i)
//4. 删除元素1,生成新的集
a - 1
//5. 拼接另一个集(6, 7, 8)
a ++ Set(6, 7, 8)
//6. 拼接一个列表(6,7,8, 9)
a ++ List(6, 7, 8, 9)
Variable Set
definition
Create a consistent set of variable can not change the way set, but need to import a variable set in advance class.
import scala.collection.mutable.Set
The sample code
import scala.collection.mutable.Set
//1. 定义一个可变集,包含以下元素: 1,2,3, 4 (mutable)可以省略
val a = mutable.Set(1,2,3,4)
//2. 添加元素5到可变集中
a += 5
//3. 从可变集中移除元素1
a -= 1