我有一個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)
}
uj5u.com熱心網友回復:
您可以使用removeLastOrNull()或removeLast()函式:
// sortedIntervals must be MutableList to call removeLastOrNull() or removeLast()
val sortedIntervals: MutableList<...> = ...
sortedIntervals.removeLastOrNull()
它們之間的區別在于,如果此串列為空,則removeLast()函式拋出NoSuchElementException,但removeLastOrNull()不拋出例外,null如果此串列為空,則回傳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397214.html
下一篇:滑動時如何不重繪螢屏
