is there a way to sort only a ArrayList subrange?
# announcements
e
is there a way to sort only a ArrayList subrange?
v
Copy code
fun main() {
    val x = mutableListOf(5, 4, 3, 2, 1)
    println(x)
    x.subList(1, 4).sort()
    println(x)
}
=>
Copy code
[5, 4, 3, 2, 1]
[5, 2, 3, 4, 1]
☝️ 3
c
I thought
subList
copied the list 🤔 that's very good to know
s
from the documentation it looks like there is no copying
?
v
Actually https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/sub-list.html as he asked about
ArrayList
, but it is basically the same, yes. 🙂
Returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
Structural changes in the base list make the behavior of the view undefined.
I think
slice
would give you an independent list
e
perfect, thanks @Vampire
s
and slice copies?
v
Yes:
Copy code
fun main() {
    val x = mutableListOf(5, 4, 3, 2, 1)
    println(x)
    val slice: List<Int> = x.slice(1..3)
    println(slice)
    (slice as MutableList).sort()
    println(slice)
    println(x)
}
=>
Copy code
[5, 4, 3, 2, 1]
[4, 3, 2]
[2, 3, 4]
[5, 4, 3, 2, 1]
s
ha okay, great