You Android drivers, for android traversal combined, concurrent modification anomalies must be no stranger;
I read an article earlier,
In alibaba Java development manual, there is such a provision:
Enhancing the for loop is also a syntactic candy provided by Java. If you decomcompile the class file (using jad), you can get the following code:
1. Reason :(in fact, I don’t want to repeat this in front of all the old drivers. -_ – | |)
The reason for this exception is that the iterator is dependent on the collection. After a successful judgment, new elements are added to the collection, and the iterator is unaware of this, so an error is reported. When iterators iterate over the elements in a collection, do not use the collection object to modify the elements in the collection.
If you look at the ArrayList source code and the implementation of the iterator() method, you can see that ArrayList inherits from the collection abstract class a member variable modCount, which will be modCount++ every time an element is added or deleted. The next method that iterates iterator will first call the checkForComodification() method, which compares modCount with expectedModCount, which is a member variable of the iterator. If initially assigned to modCount, an exception will be thrown for concurrent modification.
The iterator class also has methods to modify the elements. After the modification is complete, the modCount is re-assigned to the expectedModCount so that the exception is not reported during the next iteration.
2. Solutions:
1. Use the normal for loop directly
Use the for loop to loop through, and then use the list directly, eg:
Foreach Iterator Iterator Iterator Iterator Iterator
3. Problems recur
MapIndexed is a syntax that is Iterator based.
So, if you were to remove elements from the collection while iterating in this way, you would get concurrent modification exceptions;
I still cozying up to Kotlin’s advanced usage, while ignoring the details, resulting in problems, carelessness, lack of understanding killed people.