因为时间很短,所以内容不是很复杂,写一个有价值的小知识,主要是为了保持每日学习和写作的习惯,大作还是会写到相关的主题里面,尽量做到周更。敬请关注本人的主要作品集:
为了能够最大限度的保证文章的质量,日更主要采用翻译的方法来完成。本系列将主要翻译Kotlin官网的内容。具体的地址
https://kotlinlang.org/docs/home.html
七 集合-Set
列表是有序的,允许重复项,而Set是无序的,而且不能重复。
要创建只读Set对象,请使用setOf()函数。
要创建可变集合(MutableSet),请使用mutableSetOf()函数。
在创建集合时,Kotlin可以推断存储项目的类型。若要显式声明类型,请在集合声明后添加尖括号内的类型:
// Read-only set
val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
// Mutable set with explicit type declaration
val fruit: MutableSet<String> = mutableSetOf("apple", "banana", "cherry", "cherry")
println(readOnlyFruit)
// [apple, banana, cherry]
您可以在上面的示例中看到,因为集合只包含唯一的元素,所以删除了重复的“cherry”项。
为了防止不必要的修改,请通过将可变集强制转换为Set来获得可变集的只读视图:
val fruit: MutableSet<String> = mutableSetOf("apple", "banana", "cherry", "cherry")
val fruitLocked: Set<String> = fruit
由于集合是无序的,您不能访问特定索引处的项。
要获取集合中的项数,请使用.count()函数:
val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
println("This set has ${readOnlyFruit.count()} items")
// This set has 3 items
要检查项目是否在集合中,请使用in运算符:
val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
println("banana" in readOnlyFruit)
// true
要在可变集合中添加或删除项,请分别使用.add()和.remove()函数:
val fruit: MutableSet<String> = mutableSetOf("apple", "banana", "cherry", "cherry")
fruit.add("dragonfruit") // Add "dragonfruit" to the set
println(fruit) // [apple, banana, cherry, dragonfruit]
fruit.remove("dragonfruit") // Remove "dragonfruit" from the set
println(fruit) // [apple, banana, cherry]
网友评论