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.

相关推荐
summerkissyou1987几秒前
Android-线程安全-volatile
android·线程
Rust研习社3 分钟前
Rust 智能指针 Cell 与 RefCell 的内部可变性
开发语言·后端·rust
leaves falling43 分钟前
C++模板进阶
开发语言·c++
坐吃山猪1 小时前
Python27_协程游戏理解
开发语言·python·游戏
gCode Teacher 格码致知1 小时前
Javascript提高:小数精度和随机数-由Deepseek产生
开发语言·javascript·ecmascript
椰猫子2 小时前
Javaweb(Filter、Listener、AJAX、JSON)
java·开发语言
盛世宏博北京2 小时前
以太网温湿度传感器运维技巧,提升设备稳定性与使用寿命
开发语言·php·以太网温湿度传感器
代码改善世界3 小时前
【MATLAB初阶】矩阵操作(一)
开发语言·matlab·矩阵
覆东流3 小时前
第1天:Python环境搭建 & 第一个程序
开发语言·后端·python
我命由我123453 小时前
Android 开发中,关于 Gradle 的 distributionUrl 的一些问题
android·java·java-ee·android studio·android jetpack·android-studio·android runtime