Java concurrent operation list collection causes java. util. Concurrent ModificationException to use iterators

Keywords: Java JavaEE Android JDK

Requirement: I have a collection, as follows, I want to determine whether there is a "world" element in it, if there is, I add a "javaee" element, please write code implementation.


The code is as follows:

  1. public class Test {  
  2.         public static void main(String[] args) {  
  3.             List<String> list = new ArrayList<String>();  
  4.               
  5.             list.add("java");  
  6.             list.add("world");  
  7.             list.add("android");  
  8.               
  9.             Iterator<String> iterator = list.iterator();  
  10.             while(iterator.hasNext()){  
  11.                 String content = iterator.next();  
  12.                 if("world".equals(content)){  
  13.                     list.add("hello");  
  14.                 }  
  15.             }  
  16.             System.out.println(list);  
  17.         }  
  18. }  

Running error message:


First, we open the jdk document to see the exception, because java is an object-oriented language and the exception is encapsulated as an object.

Concurrent ModificationException: This exception is thrown when a method detects concurrent modifications to an object but does not allow such modifications.

Reasons for this:
Iterators depend on sets. After judging success, new elements are added to the set, but the iterator does not know, so it makes an error, which is called concurrent modification exception.
In fact, this problem describes that when iterators traverse elements, elements cannot be modified through collections.
How to solve it?
A: Iterator iteration elements, iterator modification elements
The element follows the element just iterated.
B: Set traversal elements, set modification elements (ordinary for)
Elements are added at the end


Solution: for loop I will not try to solve it in another way, the code is as follows:

  1. public class Test {  
  2.         public static void main(String[] args) {  
  3.             List<String> list = new ArrayList<String>();  
  4.               
  5.             list.add("java");  
  6.             list.add("world");  
  7.             list.add("android");  
  8.              ListIterator lit = list.listIterator();  
  9.              while (lit.hasNext()) {  
  10.              String s = (String) lit.next();  
  11.              if ("world".equals(s)) {  
  12.              lit.add("javaee");  
  13.               }  
  14.              }  
  15.              System.out.println(list);  
  16.         }  
  17. }  

Because ListIterator has the add() method, it solves the problem.

Posted by Peter on Wed, 06 Feb 2019 01:51:16 -0800