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.

相关推荐
Wang's Blog21 小时前
Java 项目实战: 交友项目 - FastDFS:入门案例
java·开发语言·交友
好的佩奇1 天前
Dart 之扩展类型
android·flutter·dart
apcipot_rain1 天前
C++转Java日记(03)
java·开发语言·c++
布莱克6051 天前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
xys_6781 天前
深挖C++:类和对象(中)
开发语言·c++
灿飞屋1 天前
Rust 编程其实很简单
开发语言·rust
alexhilton1 天前
2027 Android 开发者路线图:学习、面试与 AI
android·kotlin·android jetpack
MOONICK1 天前
QT元数据
开发语言·qt
D e re k ZH1 天前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
灿飞屋1 天前
Kotlin与Java虚拟机三:控制流
android·java·开发语言·后端·python·kotlin·安卓