首页 > 代码库 > CopyOnWriteArrayList操作java.lang.UnsupportedOperationException

CopyOnWriteArrayList操作java.lang.UnsupportedOperationException

问题一:CopyOnWriteArrayList不能强制转换成ArrayList
解决的方法:将CopyOnWriteArrayList传入ArrayList中
ArrayList<T> arrayList = new ArrayList<T>(list);

问题二:CopyOnWriteArrayList不支持Collections.sort
解决的方法:

ArrayList<T> arrayList = new ArrayList<T>(list);
        Collections.sort(arrayList ,new Comparator<T>() {
            public int compare(T o1, T o2) {}       });

问题三:CopyOnWriteArrayList不支持
while (iterator.hasNext()) {
iterator.remove();
}
原因:CopyOnWriteArrayList在做迭代之前是做了一份”快照”,所以此时的iter是不可变的,也就是说假设在此遍历中调用iter.remove()会抛出异常
解决的方法:

        CopyOnWriteArrayList<T> t1 ;
        Iterator<GameExperience> iterator = t1.iterator();
        while (iterator.hasNext()) {
                T t= iterator.next();
                t1.remove(t);
            }
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

CopyOnWriteArrayList操作java.lang.UnsupportedOperationException