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.

相关推荐
顾林海几秒前
从0到1搭建Android网络框架:别再让你的请求在"路上迷路"了
android·面试·架构
氵文大师10 分钟前
A机通过 python -m http.server 下载B机的文件
linux·开发语言·python·http
封奚泽优22 分钟前
下降算法(Python实现)
开发语言·python·算法
花花鱼24 分钟前
android room中实体类变化以后如何迁移
android
笃行客从不躺平44 分钟前
遇到大SQL怎么处理
java·开发语言·数据库·sql
郝学胜-神的一滴44 分钟前
Python中常见的内置类型
开发语言·python·程序人生·个人开发
Jomurphys1 小时前
设计模式 - 适配器模式 Adapter Pattern
android
雨白1 小时前
电子书阅读器:解析 EPUB 底层原理与实战
android·html
g***B7381 小时前
Kotlin协程在Android中的使用
android·开发语言·kotlin
火白学安全1 小时前
《Python红队攻防零基础脚本编写:进阶篇(一)》
开发语言·python·安全·web安全·网络安全·系统安全