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.

相关推荐
cookies_s_s12 分钟前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
盐焗鹌鹑蛋1 小时前
【C++】继承
开发语言·c++
2601_963771372 小时前
Offloading WP-Cron and Securing Ticket Webhooks on Enterprise IT Sites
android
栈溢出了2 小时前
Java Lambda 表达式笔记
java·开发语言·intellij-idea
zhixingheyi_tian2 小时前
一份GC日志的解读
java·开发语言
czhaii2 小时前
串口1中断收发-C语言-MODBUS协议
c语言·开发语言
花燃柳卧2 小时前
跨平台路由组件工程源码补充上传
android·flutter·kotlin
apihz2 小时前
随机驾考题目(C 照科一 / 科四 2000+ 题)免费API调用教程
android·java·c语言·开发语言·网络协议·tcp/ip
matlab代码3 小时前
基于matlab人脸疲劳驾驶检测系统(可使用其它人脸视频)【源码39期】
开发语言·matlab·人脸疲劳检测
宸翰3 小时前
uni-app 设置 Android 底部虚拟导航栏背景色
android·前端·uni-app