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.

相关推荐
chao1898443 小时前
基于 SPEA2 的多目标优化算法 MATLAB 实现
开发语言·算法·matlab
赏金术士3 小时前
Kotlin 习题集 · 高级篇
android·开发语言·kotlin
楼兰公子4 小时前
buildroot 在编译rust时裁剪平台类型数量的方法
开发语言·后端·rust
吴声子夜歌4 小时前
Go——并发编程
开发语言·后端·golang
ooseabiscuit5 小时前
Laravel4.x:现代PHP框架的奠基之作
java·开发语言·php
问心无愧05135 小时前
ctf show web 入门42
android·前端·android studio
c1s2d3n4cs5 小时前
Qt模仿nlohmann::json进行序列化和反序列化
开发语言·qt·json
没什么本事6 小时前
关于C# panel 添加lable问题 -- 明确X和Y 位置错误
android·java·c#
AiTop1006 小时前
Claude Code 推出 Agent View:命令行编程正式进入“多线程并发“时代
开发语言·人工智能·ai·aigc
jf加菲猫6 小时前
第21章 Qt WebEngine
开发语言·c++·qt·ui