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.

相关推荐
萤丰信息2 分钟前
技术赋能安全:智慧工地构建城市建设新防线
java·大数据·开发语言·人工智能·智慧城市·智慧工地
Pocker_Spades_A24 分钟前
飞算JavaAI家庭记账系统:从收支记录到财务分析的全流程管理方案
java·开发语言
CHEN5_022 小时前
【Java基础常见辨析】重载与重写,深拷贝与浅拷贝,抽象类与普通类
java·开发语言
檀越剑指大厂2 小时前
容器化 Android 开发效率:cpolar 内网穿透服务优化远程协作流程
android
Despacito0o2 小时前
C语言基础:变量与进制详解
java·c语言·开发语言
nightunderblackcat2 小时前
进阶向:人物关系三元组,解锁人物关系网络的钥匙
开发语言·python·开源·php
MiyamuraMiyako3 小时前
从 0 到发布:Gradle 插件双平台(MavenCentral + Plugin Portal)发布记录与避坑
android
NRatel3 小时前
Unity 游戏提升 Android TargetVersion 相关记录
android·游戏·unity·提升版本
科大饭桶3 小时前
C++入门自学Day11-- String, Vector, List 复习
c语言·开发语言·数据结构·c++·容器
范范之交3 小时前
JavaScript基础语法two
开发语言·前端·javascript