简体   繁体   English

遍历集合以添加项目但抛出 ConcurrentModificationException

[英]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.

相关问题 如果我们在迭代时最后在ArrayList中添加元素,则抛出ConcurrentModificationException - Throwing ConcurrentModificationException if we add elements in ArrayList at the end while iterating Java ConcurrentModificationException:是否可以在迭代时向哈希表添加元素? - Java ConcurrentModificationException: Is it possible to add elements to a hashtable while iterating through it? 通过HashMap迭代时出现ConcurrentModificationException - ConcurrentModificationException while iterating through HashMap 遍历列表并将项目添加到另一个 - Iterating through List and add items to another 迭代ArrayList时出现ConcurrentModificationException <Integer> - ConcurrentModificationException when iterating through an ArrayList <Integer> 遍历列表但未修改列表时发生ConcurrentModificationException - ConcurrentModificationException while iterating through a list but not modifying it 迭代Arraylist时的ConcurrentModificationException(不删除) - ConcurrentModificationException while iterating through Arraylist (not removing) 遍历List时发生ConcurrentModificationException,尽管未对其进行任何修改 - ConcurrentModificationException while iterating through List, altough not modifying it 如果在迭代时修改集合而不抛出 ConcurrentModificationException 会发生什么 - what will happen if modify a collection while iterating without throwing the ConcurrentModificationException 集合:ConcurrentModificationException - Collections: ConcurrentModificationException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM