Java Basics (2)—ConcurrentModificationException occurs when using Iterator

code show as below

Traverse Listthe collection and modify the collection when a certain condition is met. The code is as follows:

public class MyListDemo {
    
    
  public static void main(String[] args) {
    
    
  
    List<String> list = Lists.newArrayList("a", "b", "c", "d");

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
    
    
      String next =  iterator.next();
      if (next.equals("d")) {
    
    
        iterator.set("f");
      }
    }
    System.out.println("list = " + list);
  }
}

The final input result is as follows:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
	at java.util.ArrayList$Itr.next(ArrayList.java:861)
	at org.apache.ibatis.gwmtest.current.MyListDemo.main(MyListDemo.java:19)

Process finished with exit code 1

It is found that ConcurrentModificationException will be thrown , so how can it be modified? You can operate with the help of a subclass of the Iterator interface ListIterator. The code is as follows:

public class ListDemo {
    
    
  public static void main(String[] args) {
    
    
    List<String> list = Lists.newArrayList("a", "b", "c", "d");

    ListIterator<String> iterator = list.listIterator();

    while (iterator.hasNext()) {
    
    
      String next =  iterator.next();
      if (next.equals("d")) {
    
    
        iterator.set("f");
        iterator.add("g");
      }
    }
    System.out.println("list = " + list);
  }
}

Output result:

list = [a, b, c, f, g]

Operations on collections are done through the ListIterator object, not the List itself.

Using ListIterator can avoid ConcurrentModificationException exceptions, but is it not without security risks?

Here are some security risks:

  1. Adding or deleting operations during the traversal process may cause errors: When using ListIterator to add or remove elements, the enumeration order during the traversal process may be affected, so addition and deletion operations during the traversal process are not recommended.

  2. Bidirectional traversal: ListIterator supports bidirectional traversal, which means that you can move forward and backward during the traversal process, which may cause errors if you accidentally modify the collection during the traversal process.

  3. Concurrent modifications: ListIterator is a single-threaded tool and does not support concurrent modifications, so if multiple threads modify the collection at the same time, inconsistency problems may occur.

Therefore, even if you use ListIterator , you still need to pay attention to the collection operations during the traversal process to ensure the correctness of the program.

Guess you like

Origin blog.csdn.net/qq_35971258/article/details/129028008