我是Kotlin的新手,需要詢問一些關於訂購MutableList<MyObject>
的問題。據我所知,我可以爲Int
和String
做myMutableList.sortBy {it.int}
和myMutableList.sortByDescending {it.int}
。但返回始終是Unit
而不是MutableList
。對Kotlin中MutableList中的數據進行排序
我在哪裏出錯了,我該如何繼續?
我是Kotlin的新手,需要詢問一些關於訂購MutableList<MyObject>
的問題。據我所知,我可以爲Int
和String
做myMutableList.sortBy {it.int}
和myMutableList.sortByDescending {it.int}
。但返回始終是Unit
而不是MutableList
。對Kotlin中MutableList中的數據進行排序
我在哪裏出錯了,我該如何繼續?
可變的意思是可變的,所以它有意義,而不是sortBy
返回一個新的列表,項目的順序已經在當前列表中「就地」改變。
嘗試查看myMutableList
中物品的訂單,之後sortBy
,你會看到他們現在按要求的順序。
要按一個可變的列表,你可以使用:
Collections.sort(myMutableList)
Collections.reverse(myMutableList) //To sort the list by descending order
而且在科特林可以使用合同科特林STDLIB指令,它變成:
myMutableList.sort()
myMutableList.reverse() //To sort the list by descending order
然後你就可以調用myMutableList
它的訂單發生了變化,如下所示:
val myMutableList = mutableListOf(8,5,4,6)
System.out.println("myMutableList: ${myMutableList[0]}")
myMutableList.sort()
System.out.println("myMutableList: ${myMutableList[0]}")
輸出:
myMutableList: 8
myMutableList: 4