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.

相关推荐
Python大数据分析@1 分钟前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
编程零零七29 分钟前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
我爱Jack40 分钟前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
米饭「」42 分钟前
C++AVL树
java·开发语言·c++
心愿许得无限大1 小时前
Qt 常用界面组件
开发语言·c++·qt
2401_858286111 小时前
OS15.【Linux】gdb调试器的简单使用
linux·运维·服务器·开发语言·gdb
牛马baby1 小时前
MATLAB下载安装教程(附安装包)2025最新版(MATLAB R2024b)
开发语言·matlab
shenyan~2 小时前
关于 c、c#、c++ 三者区别
开发语言·c++
Ashlee_code2 小时前
什么是Web3?金融解决方案
开发语言·金融·架构·eclipse·web3·区块链·php
Evand J2 小时前
【MATLAB例程】AOA与TDOA混合定位例程,适用于三维环境、4个锚点的情况,附下载链接
开发语言·matlab