0
点赞
收藏
分享

微信扫一扫

a26_Scala set 集合


目录

  • ​​scala outline​​
  • ​​scala集合概述​​
  • ​​scala 不可变 set 创建 访问​​
  • ​​scala 元素添加 删除​​
  • ​​scala 可变 set 创建 元素添加 删除​​
  • ​​建议​​

scala outline

​​scala outline​​

scala集合概述

​​链接​​

scala 不可变 set 创建 访问

def main(args: Array[String]): Unit = {
// Set默认是不可变集合,数据无序
val set: Set[Int] = Set(1, 2, 3)

//遍历方式1
set.foreach((x: Int) => {
print(x + " ")
})

//遍历方式2
val it: Iterator[Int] = set.iterator
while (it.hasNext) {
print(it.next() + " ")
}
}

scala 元素添加 删除

def main(args: Array[String]): Unit = {
var set = Set(1, 2, "hello")
// 元素添加 如果添加的对象已经存在,则不会重复添加,也不会重复报错
set += 6
println(set) // 输出 Set(1, 2, hello, 6)
// 删除
set -= "hello"
println(set) // 输出 Set(1, 2, 6)
}

scala 可变 set 创建 元素添加 删除

def main(args: Array[String]): Unit = {
// 创建可变set
val set = mutable.Set(1, 2, 3)

// 集合添加元素
set.add(8)

// 删除数据
set.remove(1)

// set的访问
val it: Iterator[Int] = set.iterator
while (it.hasNext) {
print(it.next() + " ")
}
}

建议

​建议:​​在操作集合的时候,不可集合的增删改查变用符号,可变集合的增删改查变用方法


举报

相关推荐

0 条评论