How to sort CopyOnWriteArrayList

前端 未结 5 1506
名媛妹妹
名媛妹妹 2021-02-06 08:46

I want to sort CopyOnWriteArrayList. But when I tried to run the following code

It is throwing unsorted operation exception.



        
5条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 09:39

    Kotlin helper function

    inline fun > CopyOnWriteArrayList.sortListBy(crossinline selector: (T) -> R?) {
        if (size > 1) {
            val list = ArrayList(this)
            list.sortBy(selector)
            clear()
            addAll(list)
        }
    }
    

    On Android

    inline fun > CopyOnWriteArrayList.sortListBy(crossinline selector: (T) -> R?) {
        if (size > 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                sortBy(selector)
            } else {
                val list = ArrayList(this)
                list.sortBy(selector)
                clear()
                addAll(list)
            }
        }
    }
    

提交回复
热议问题