Concurrent modification abnormal ConcurrentModificationException

1. Description: When using the iterator object through the collection, a collection of objects used to modify elements in the collection causes an exception

 

public static void main(String[] args) {
        
        List<Integer> list=new ArrayList<>();
        list.add(1);list.add(2);list.add(3);list.add(4);
        
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer integer = (Integer) iterator.next();
            list.remove(2);
        }
    }

2. Cause: An iterator is dependent on the set, and change collection's iterator does not know.

3. Solution:

   One way: iterator traversal iterator modified ( ListIterator )

remove:

public static void main(String[] args) { 
        List<Integer> list=new ArrayList<>();
        list.add(1);list.add(2);list.add(3);list.add(4);
        
        ListIterator<Integer> iterator = list.listIterator();
while (iterator.hasNext()) { Integer integer = (Integer) iterator.next(); if(integer==2) { iterator.remove(); } } System.out.println(list); }

 

 

 

add:

public static void main(String[] args) {     
        List<Integer> list=new ArrayList<>();
        list.add(1);list.add(2);list.add(3);list.add(4);
        
        ListIterator<Integer> iterator = list.listIterator();
while (iterator.hasNext()) { Integer integer = (Integer) iterator.next(); if(integer==1){ iterator.add(1); } } System.out.println(list); }


   Second way: direct use for loop through the collection, modification (size () and GET ())

public static void main(String[] args) {
        
        List<Integer> list=new ArrayList<>();
        list.add(1);list.add(2);list.add(3);list.add(4);
        
        for (int i = 0; i < list.size(); i++) {
            list.set(0, 3);//3234
            
            if (list.get(i)==2) {
                list.remove(i);//334
            }
            if (list.get(i)==3) {
                list.add(5);//33455
            }

        }
        System.out.println(list);
    }

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/crazy-lc/p/11900697.html