How to avoid an java.util.ConcurrentModificationException with ArrayList?
You need to add/delete an item in an ArrayList when you are iterating the list. You will receive the java.util.ConcurrentModificationException exception. For example, the following code will throw an exception after adding an item into list:
public class Sample {
public static void main(String[] args) {
List<Integer> iList = new ArrayList<Integer>();
for (int i = 0; i != 100; i++)
iList.add(i);
int addValue = 1000;
for (Integer i: iList) {
if (i%10 == 0) {
iList.add(addValue++);
}
}
}
To avoid java.util.ConcurrentModificationException exception, we can add an item through the iterator of list. If we do the same as the above code, the next access item in list via the iterator will generate the same exception.
public class Sample {
public static void main(String[] args) {
List<Integer> iList = new ArrayList<Integer>();
for (int i = 0; i != 100; i++)
iList.add(i);
int addValue = 1000;
for (ListIterator<Integer> itr = iList.listIterator(); itr.hasNext();) {
Integer i = itr.next();
if (i%10 == 0) {
itr.add(addValue++);
}
}
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?