默认情况下,Scala使用的是不可变集合,如果你想使用可变集合,需要引用 scala.collection.mutable.Set 包
不可变Set
- 说明
(1)Set默认是不可变集合,数据无序
(2)数据不可重复
(3)遍历集合
案例实操 ```scala object TestSet { def main(args: Array[String]): Unit = { //Set默认是不可变集合,数据无序 val set = Set(1, 2, 3, 4, 5, 6)
//数据不可重复 val set1 = Set(1, 2, 3, 4, 5, 6, 3)
//遍历集合 for (x <- set1) { println(x) } } }
<a name="Lb25M"></a># 可变mutable.Set1. **说明**(1)创建可变集合mutable.Set<br />(2)打印集合<br />(3)集合添加元素(add)<br />(4)向集合中添加元素,返回一个新的Set<br />(5)删除数据(remove)2. **案例实操**```scalaobject TestSet {def main(args: Array[String]): Unit = {//创建可变集合val set = mutable.Set(1, 2, 3, 4, 5, 6)//集合添加元素set += 8//向集合中添加元素,返回一个新的Setval ints = set.+(9)println(ints)println("set2=" + set)//删除数据set -= (5)//打印集合set.foreach(println)println(set.mkString(","))}}
