How to sort CopyOnWriteArrayList

前端 未结 5 1511
名媛妹妹
名媛妹妹 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:15

    Collections.sort uses ListIterator.set

        ...
        for (int j=0; j

    but CopyOnWriteArrayList's ListIterator does not support the remove, set or add methods.

    Workaround:

        Object[] a = list.toArray();
        Arrays.sort(a);
        for (int i = 0; i < a.length; i++) {
            list.set(i, (String) a[i]);
        }
    

提交回复
热议问题