concurrentModificationException

与世无争的帅哥 提交于 2019-12-19 10:47:12

问题


With the snippet below I am, attempting to process a spreadsheet, with the twist of needing to exclude ad hoc columns. I know the crude way I am doing it, put the exceptions in an ArrayList and process the list on each and ever increment over the current row columns is perverse, but you know just get it done.

However I am getting the titled error, which I believe should never happen. I am just looping through the ArrayList and comparing, not modifying anything. Where is the error? Is there a better way to handle the exceptions list?

ArrayList noProcess = new ArrayList();
Iterator itr00 = noProcess.iterator();
Iterator itr01 = noProcess.iterator();
noProcess.add(new Integer("5"));
noProcess.add(new Integer("18"));
....
 boolean include=true;
  for(int i=0;i<archive.length;i++){
    for (int j = 0; j < archive[i].length; j++) {
      while (itr00.hasNext()) {
        if (j == ( (Integer) itr00.next()).intValue())
          include = false;
      }
      if (include) {...

回答1:


You can't alter the contents of an Iterable once you create an iterator on it (other than via the iterator), otherwise you'll get a ConcurrentModificationException as soon as you move the iterator - you create an iterator, then do noProcess.add(new Integer("5"));, then later advance the iterator.

Also, you create two iterators - you shouldn't do that either - it's crazy.




回答2:


From the JavaDoc,

ConcurrentModificationException : This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

E.g it is not generally permssible for one thread to modify a Collection while another thread is iterating over it.




回答3:


From the Java Docs:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Use the iterator's add method to add an element into the List




回答4:


Adding records in list after getting iterator, correct that.. it should work then.



来源:https://stackoverflow.com/questions/6790856/concurrentmodificationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!