[英]Iterating through collections to add items but throwing ConcurrentModificationException
package com.ripal; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class Outputs { public void show() { final ArrayList<String> list = new ArrayList<String>(); list.add("banana"); list.add("apple"); Iterator<String> itr = list.iterator(); Collections.sort(list); while (itr.hasNext()) { System.out.println(itr.next() + " "); } } } class Test { public static void main(String[] args) { Outputs outputs = new Outputs(); outputs.show(); } }
ArrayList
has a fail fast iterator. ArrayList
有一个快速失败的迭代器。 You can modify the collection only via the iterator.您只能通过迭代器修改集合。 Any other modification done outside is detected sooner after calling the iterator methods and a ConcurrentModificationException
is thrown.在调用迭代器方法后会更快地检测到在外部进行的任何其他修改,并抛出ConcurrentModificationException
。 In your case after creating the iterator you sort the array in place and that sorting routine modifies the contents of the array, leading to ConcurrentModificationException
upon using the iterator.在您的情况下,在创建迭代器后,您对数组进行了就地排序,并且该排序例程会修改数组的内容,从而在使用迭代器时导致ConcurrentModificationException
。 To fix the issue, just perform the sorting before you create the iterator.要解决这个问题,只需在创建迭代器之前执行排序。 Here's how it looks.这是它的外观。
Collections.sort(list);
Iterator<String> itr = list.iterator();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.