集合类型之Set、MutableSet
Kotlin的集合分为两大类:可变集合和不可变集合,对于Set集合来说,就分为不可变的Set以及可变的MutableSet。
Kotlin的List集合和Set集合的功能基本相同,Set集合只是为List集合增加了额外的限制:集合元素不允许重复。
Set集合
声明和创建
通过setOf创建不可变Set,setOf提供了3个重载函数来创建,我们根据源码来一一分析:
-setOf():
创建一个空的Set
源码:
/**
* Returns an empty read-only set. The returned set is serializable (JVM).
* @sample samples.collections.Collections.Sets.emptyReadOnlySet
*/
@kotlin.internal.InlineOnly
public inline fun <T> setOf(): Set<T> = emptySet()
setOf(element: T):
创建一个元素只有一个的Set
/**
* Returns an immutable set containing only the specified object [element].
* The returned set is serializable.
*/
public fun <T> setOf(element: T): Set<T> = java.util.Collections.singleton(element)
setOf(vararg elements: T):
创建含有多个元素的Set
/**
* Returns a new read-only set with the given elements.
* Elements of the set are iterated in the order they were specified.
* The returned set is serializable (JVM).
* @sample samples.collections.Collections.Sets.readOnlySet
*/
public fun <T> setOf(vararg elements: T): Set<T> = if (elements.size > 0) elements.toSet() else emptySet()
例:
fun main(args: Array<String>) {
val numSetNull = setOf<Int>()
val numSetOne = setOf("hello")
val numSetM