如何在集合数据删除时---避免ConcurrentModificationException异常呢?
下文笔者讲述避免出现ConcurrentModificationException异常的解决方法分享,如下所示
ConcurrentModificationException异常的演示
public static void main(String[] args) { Collection<Integer> l = new Arraylist<>(); for (int i = 0; i < 10; ++i) { l.add(44); l.add(55); l.add(66); } for (int i : l) { if (i == 55) { l.remove(i); } } System.out.println(l); } 以上代码,会导致异常信息 Exception in thread "main" java.util.ConcurrentModificationException那么如何避免这类异常呢?下文笔者讲述具体的实现思路
只需使用Iterator.remove() 移除元素 即可避免此类异常例:list删除元素的正确写法
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { String string = iterator.next(); if (string.isEmpty()) { // Remove the current element from the iterator and the list. iterator.remove(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。