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.

相关推荐
dmlcq17 小时前
一文读懂 PageQueryUtil:分页查询的优雅打开方式
开发语言·windows·python
不会写DN17 小时前
JS 最常用的性能优化 防抖和节流
开发语言·javascript·ecmascript
HLC++17 小时前
数据结构--树
c语言·开发语言·数据结构
2501_9454248017 小时前
C++构建缓存加速
开发语言·c++·算法
2401_8512729917 小时前
多平台UI框架C++开发
开发语言·c++·算法
zhouping@17 小时前
[极客大挑战 2020]Greatphp
android·ide·web安全·android studio
骇客野人17 小时前
Java实现B+树,体会B+树做索引的精妙
java·开发语言·b树
毕设源码-邱学长17 小时前
【开题答辩全过程】以 基于 Android的超市服务评价系统的设计与实现为例,包含答辩的问题和答案
android
楼田莉子17 小时前
C++数据结构:基数树
开发语言·数据结构·c++·学习
m0_5180194817 小时前
C++中的命令模式实战
开发语言·c++·算法