【问题标题】:Pop Mutablelist from a MutableList kotlin从 MutableList kotlin 中弹出 Mutablelist
【发布时间】:2021-12-29 21:49:36
【问题描述】:

我在kotlin 中有一个mutableListOf<MutableList<Int>>。如何从这个列表中弹出最后一个元素? 我试过 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)
}

【问题讨论】:

  • sortedWith() 返回一个新的(排序的)只读List - 不是一个可变列表,所以你不能调用改变结果列表的操作(在你的情况下,在@ 987654326@)

标签: list kotlin mutablelist


【解决方案1】:

您可以使用removeLastOrNull() 或removeLast() 函数:

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

它们的区别在于removeLast()函数如果这个列表为空则抛出NoSuchElementException,而removeLastOrNull()不会抛出异常,如果这个列表为空则返回null。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2020-11-14
    • 1970-01-01
    相关资源
    最近更新 更多