Kotlin:Set其实是有插入的顺序?

MutableSet怎么能调用indexOf去获取它的插入顺序呢?参考官网Collections overview | Kotlin Documentationhttps://kotlinlang.org/docs/collections-overview.html#set翻不了墙的看下面 (MutableSet的默认实现是LinkedHashSet,LinkedHashSet是有保留元素插入的顺序)

Set

Set<T> stores unique elements; their order is generally undefined. null elements are unique as well: a Set can contain only one null. Two sets are equal if they have the same size, and for each element of a set there is an equal element in the other set.()

Kotlin 复制代码
val numbers = setOf(1, 2, 3, 4)
println("Number of elements: ${numbers.size}")
if (numbers.contains(1)) println("1 is in the set")

val numbersBackwards = setOf(4, 3, 2, 1)
println("The sets are equal: ${numbers == numbersBackwards}")


Number of elements: 4
1 is in the set
The sets are equal: true

MutableSet is a Set with write operations from MutableCollection.

The default implementation of MutableSet -- LinkedHashSet -- preserves the order of elements insertion. Hence, the functions that rely on the order, such as first() or last(), return predictable results on such sets.

Kotlin 复制代码
val numbers = setOf(1, 2, 3, 4)  // LinkedHashSet is the default implementation
val numbersBackwards = setOf(4, 3, 2, 1)

println(numbers.first() == numbersBackwards.first())
println(numbers.first() == numbersBackwards.last())
println(numbersBackwards.indexOf(2))


false
true
2

An alternative implementation -- HashSet -- says nothing about the elements order, so calling such functions on it returns unpredictable results. However, HashSet requires less memory to store the same number of elements.

相关推荐
hsjkdhs42 分钟前
C++之类的继承与派生
开发语言·c++
lly2024061 小时前
HTML 元素:构建网页的基础
开发语言
低调小一1 小时前
LRU缓存科普与实现(Kotlin 与 Swift)
开发语言·缓存·kotlin
爱好学习的青年人1 小时前
一文详解Go语言字符串
开发语言·后端·golang
雨白1 小时前
深入理解协程的运作机制 —— 调度、挂起与性能
android·kotlin
沐怡旸1 小时前
【Android】Android系统体系结构
android
浅川.251 小时前
xtuoj string
开发语言·c++·算法
望获linux1 小时前
【实时Linux实战系列】实时系统的可观测性:Prometheus 与 Grafana 集成
大数据·linux·服务器·开发语言·网络·操作系统
namehu2 小时前
React Native 应用性能分析与优化不完全指南
android·react native·ios
加油吧zkf2 小时前
Python入门:从零开始的完整学习指南
开发语言·前端·python