Far*_*deh 4 collections list slice kotlin
我最近意识到Kotlin中有两个非常相似的函数来获取a的一部分List,但是我不确定其中的区别:
返回此列表中指定的fromIndex(包括)和toIndex(不包括)之间的视图。返回列表由该列表支持,因此返回列表中的非结构更改会反映在此列表中,反之亦然。
基本列表中的结构更改使视图的行为不确定。
而文档的slice说明:
返回一个列表,其中包含位于指定索引范围内的索引处的元素。
要么
返回包含指定索引处的元素的列表。
似乎关键的区别在于第一个返回列表的“ 部分视图 ”,并且是否反映了非结构性更改?但是我不太确定这意味着什么。
我查看了该slice函数的源代码:
public fun <T> List<T>.slice(indices: IntRange): List<T> {
if (indices.isEmpty()) return listOf()
return this.subList(indices.start, indices.endInclusive + 1).toList()
}
Run Code Online (Sandbox Code Playgroud)
但是它从subList函数返回一个列表。
有人可以解释这两个功能之间的区别,以及您何时想使用其中一个?
The key in List<T>.slice function is the .toList() at the end.
The call to toList() will create a new List with all the elements, like a copy.
For summary:
.slice()将使用元素子集创建一个新列表.subList()只是原始列表的视图,该列表将随之变化。您可以在这里看到差异:https://pl.kotl.in/-JU8BDNZN
fun main() {
val myList = mutableListOf(1, 2, 3, 4)
val subList = myList.subList(1, 3)
val sliceList = myList.slice(1..2)
println(subList) // [2, 3]
println(sliceList) // [2, 3]
myList[1] = 5
println(subList) // [5, 3]
println(sliceList) // [2, 3]
}
Run Code Online (Sandbox Code Playgroud)