Kotlin:Set其实是有插入的顺序?

本文解释了在Kotlin中,MutableSet如何通过LinkedHashSet实现保持插入顺序,以及与仅基于哈希的HashSet在依赖顺序操作上的不同。同时讨论了它们在内存使用上的优劣。
摘要由CSDN通过智能技术生成

MutableSet怎么能调用indexOf去获取它的插入顺序呢?参考官网Collections overview | Kotlin Documentationicon-default.png?t=N7T8https://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.()

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值