开发者

concurrentModificationException

开发者 https://www.devze.com 2023-03-22 10:50 出处:网络
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

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 w开发者_如何学Pythonay 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) {...


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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号