如何选择低价网站建设,浙江省交通工程建设集团网站,东莞哪家做网站,建设工程公司简介List 在遍历时候删除元素
为list添加元素#xff0c;通过for或者通过foreach删除都存在删除异常#xff0c;在捕获异常的时候注意异常信息的简化消息传递#xff0c;容易造成异常错误的简化
Testpublic void testException(){ListInteger list new ArrayList…List 在遍历时候删除元素
为list添加元素通过for或者通过foreach删除都存在删除异常在捕获异常的时候注意异常信息的简化消息传递容易造成异常错误的简化
Testpublic void testException(){ListInteger list new ArrayList();for (int i 0; i 5; i) {list.add(i);}try {for (Integer el : list) {list.remove(el);}}catch (Exception e){System.out.println(e);System.out.println(e.getMessage());System.out.println(e.getCause());}IteratorInteger iterator list.iterator();while (iterator.hasNext()){Integer next iterator.next();System.out.println(next);iterator.remove();}System.out.println(list);}结果如下
java.util.ConcurrentModificationException
null
null
1
2
3
4
[]无法删除完的问题因为集合在不断的伸缩变化 for (int i 0; i list.size(); i) {list.remove(list.get(i));}System.out.println(list);ListInteger list Collections.synchronizedList(new ArrayList()); 安全但是依旧爆并发修改的错误
通过迭代器修改可行 但是在删除之前一定要有个iterator.next();的判断不然它不知道该删除哪一个错误
通过安全的集合类可行 ListInteger list new CopyOnWriteArrayList();
使用中间的集合暂存元素再修改 ArrayListInteger temp new ArrayList();for (Integer integer : list) {if (integer % 2 0){temp.add(integer);}}list.removeAll(temp);System.out.println(list);