1.set集合定义,不允许重复元素打印
package Stage4
fun main() {
//set集合定义,不允许重复元素打印
// val set : Set<String> = setOf<String>("java","kotlin","c++","java","c++")
val set= setOf("java","kotlin","c++","java","c++")
println(set)
}
执行结果
定义重复的元素不会打印
2.set元素获取
set中不能使用[]取值,取而代之的是通过elementAt()获取
package Stage4
fun main() {
//set集合定义,不允许重复元素打印
// val set : Set<String> = setOf<String>("java","kotlin","c++","java","c++")
val set= setOf("java","kotlin","c++","java","c++")
println(set)
println(set.elementAt(0))
println(set.elementAt(9))
}
执行结果
3.处理崩溃越界
elementAtOrElse(){}当越界后执行{}中逻辑
package Stage4
fun main() {
//set集合定义,不允许重复元素打印
// val set : Set<String> = setOf<String>("java","kotlin","c++","java","c++")
val set= setOf("java","kotlin","c++","java","c++")
println(set)
println(set.elementAt(0))
//println(set.elementAt(9))会发生越界崩溃
//处理越界崩溃
println(set.elementAtOrElse(9){"当越界后执行的逻辑"})
}
执行结果
或者使用
set.elementAtOrNull(9)?:"当越界后执行的逻辑"
package Stage4
fun main() {
//set集合定义,不允许重复元素打印
// val set : Set<String> = setOf<String>("java","kotlin","c++","java","c++")
val set= setOf("java","kotlin","c++","java","c++")
println(set)
println(set.elementAt(0))
//println(set.elementAt(9))会发生越界崩溃
//处理越界崩溃
println(set.elementAtOrElse(9){"当越界后执行的逻辑"})
println(set.elementAtOrNull(9)?:"当越界后执行的逻辑")
}
执行结果
4.kotlin语言的可变set集合
package Stage4
fun main() {
val set= mutableSetOf("java","kotlin","c++")
set+="c"
set+="c#"
set.add("py")
set-="c"
set.remove("py")
println(set)
}
执行结果