📅  最后修改于: 2023-12-03 15:30:04.982000             🧑  作者: Mango
When working with Java in Android, you may come across the ConcurrentModificationException
error. This error occurs when you try to modify a collection while concurrently iterating over it using an Iterator
, for-each
loop or the listIterator()
method.
This error typically occurs when there are multiple threads or multiple iterations happening at the same time. When one thread modifies a collection while another thread or iteration is still active, the exception will be thrown.
To fix this error, you can use a synchronized
block to ensure that only one thread is modifying the collection at a time. Another option is to use the CopyOnWriteArrayList
class which allows for concurrent reads while ensuring a consistent view of the list.
// Synchronized block example
synchronized(list) {
Iterator<String> it = list.iterator();
while(it.hasNext()) {
String str = it.next();
if(str.equals("foo")) {
list.remove(str);
}
}
}
// CopyOnWriteArrayList example
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("foo");
list.add("bar");
Iterator<String> it = list.iterator();
while(it.hasNext()) {
String str = it.next();
if(str.equals("foo")) {
list.remove(str);
}
}
In both examples, we are preventing concurrent modification of the collection by using the synchronized
block or the CopyOnWriteArrayList
class.
In summary, the ConcurrentModificationException
error can be resolved by using synchronized blocks or the CopyOnWriteArrayList
class to ensure that only one thread is modifying the collection at a time.