1

我有一个mutableListOf<MutableList<Int>>kotlin. 如何从这个列表中弹出最后一个元素?我试过 removeAt 但它没有用。

fun main() {
    val intervals:List<List<Int>> = listOf(listOf(2,9), listOf(1,8), listOf(-4, 234), listOf(22,1))
    println(intervals)    
    var sortedIntervals = intervals.toMutableList().sortedWith(Comparator<List<Int>> 
            {a, b -> a[0].compareTo(b[0])})
    println(sortedIntervals)
    sortedIntervals = sortedIntervals.map() {it -> it.toMutableList()}
    println(sortedIntervals.last())
    sortedIntervals.removeAt(sortedIntervals.size-1)
    println(sortedIntervals)
}
4

1 回答 1

3

您可以使用removeLastOrNull()removeLast()功能:

// sortedIntervals must be MutableList to call removeLastOrNull() or removeLast()
val sortedIntervals: MutableList<...> = ...
sortedIntervals.removeLastOrNull()

它们之间的区别在于,如果此列表为空,则removeLast()函数会抛出异常,但不会抛出异常,如果此列表为空则返回。NoSuchElementExceptionremoveLastOrNull()null

于 2021-12-29T21:58:39.807 回答