汇合分为可变汇合mutable.Set和不可变汇合Set。
Set
// 定义val set1 = Set(1, 2, 3, 1, 2, 3)println(set1) // Set(1, 2, 3)// 新增val set2 = set1.+(4)println(set2) // Set(1, 2, 3, 4)val set3 = set1 + 4println(set3) // Set(1, 2, 3, 4)// 删除val set4 = set3 - 1println(set4) // Set(2, 3, 4)// 加汇合val set5 = Set(2, 3, 4, 5)val set6 = set1 ++ set5println(set6) // Set(5, 1, 2, 3, 4)// 循环set6.foreach(println)// 并集val set7 = Set(1, 2, 3) union (Set(2, 3, 4))println(set7) // Set(1, 2, 3, 4)// 差集val set8 = Set(1, 2, 3) diff (Set(2, 3, 4))println(set8) // Set(1)// 交加val set9 = Set(1, 2, 3) intersect (Set(2, 3, 4))println(set9) // Set(2, 3)
mutable.Set
循环、并集、差集、交接同上,这里不做累述
// 定义val set1 = mutable.Set(1, 2, 3)// 加元素set1 += 4println(set1) // Set(1, 2, 3, 4)set1.add(5)println(set1) // Set(1, 5, 2, 3, 4)// 删除set1 -= 5println(set1) // Set(1, 2, 3, 4)set1.remove(1)println(set1) // Set(2, 3, 4)// 加汇合set1 ++= mutable.Set(1, 2, 6)println(set1) // Set(1, 5, 2, 6, 3, 4)