Java – do not modify the list, but still get concurrentmodificationexception

This is not a typical concurrent modificationexception problem until you look at another concurrent modificationexception problem

I understand concurrent modificationexceptions, but I don't understand why I get one in the following code In the following 'for', it seems that the iterator continues to exist outside the for loop (using the debugger in eclipse, I can see that the iterator retains the modcount value of its JList when restarting the loop.)

public class ForEachTest {
  public static void main(String[] args) {
    List<Integer> zList = new LinkedList<Integer>();
    List<Integer> jList = new LinkedList<Integer>();
    jList.add(1);

    while (true) {
      for (Integer j : jList) {
        zList.add(17);
        System.out.println(j);
      }
      jList = zList;
    }
  }
}

At first I thought it might be a syntax sugar problem, but I rewritten it with an explicit iterator and ran the same behavior

Finally, I can rewrite for by dividing it into a period of time and performing a separate initialization step, so I don't just want it to be rewritten to make it work But I want to know what the problem here is If possible, I prefer to use the for - each syntax

Solution

Look at your cycle:

while (true) {
  for (Integer j : jList) {
    zList.add(17);
    System.out.println(j);
  }
  jList = zList;
}

In the second iteration of the external loop, JList and zlist refer to the same list (because JList = zlist; statement)... So when you add zlist to the internal loop, you are modifying the list. You are an iteration Bang

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>