One of the mutual work piece removing elements from an ArrayList inwards Java is the ConcurrentModificationException. If you lot purpose classical for loop amongst the index or enhanced for loop in addition to elbow grease to take away an chemical component from the ArrayList using remove() method, you lot volition acquire the ConcurrentModificationException but if you lot purpose Iterator's take away method or ListIterator's remove() method, in addition to so you lot won't acquire this mistake in addition to survive able to take away the element. It's an unwritten dominion inwards Java that piece looping through the list, you lot should non add() or remove() elements until the collection supports fail-safe Iterator e.g. CopyOnWriteArrayList, which operate on a re-create of listing rather than the master copy list.
The primary work amongst this mistake is that it confuses developer that listing is getting modified past times multiple threads in addition to that's why Java is throwing this error, it's non true. Most of the fourth dimension ConcurrentModificationException comes fifty-fifty without multiple threads modifying the list.
It's misnomer, don't acquire fooled away past times this. though it seems natural thinking that possibly approximately other thread is trying to alter the collection at the same time, it's normally breaking the Java rule.
In this article, I'll explicate this mistake in addition to we'll many code instance to reproduce this code fifty-fifty amongst the unmarried thread in addition to larn how nosotros tin post away avoid concurrent change mistake piece modifying an ArrayList inwards Java.
Btw, if you lot are non familiar amongst collection classes e.g. ArrayList itself in addition to so you lot should bring together an online course of written report e.g. Java Basics: Learn to Code the Right Way on Udemy is a skilful house to start with.
For example, inwards the below code nosotros guide maintain showtime added a dyad of skilful programming books e.g. Programming Pearls, Clean Code, Effective Java, in addition to Code Complete into ArrayList in addition to and so removing whatever chemical component which has Code inwards its title.
You tin post away run into that this mistake comes fifty-fifty though nosotros simply guide maintain i thread, primary thread which is operating amongst ArrayList. The ConcurrentModification mistake comes because nosotros are non using Iterator, instead simply calling listOfBooks.remove() method.
In this code, I guide maintain used Java 1.5 enhanced for loop, you lot must know how enhanced for loop industrial plant inwards Java.
Difference betwixt for loop in addition to enhanced for loop is that afterwards internally uses an Iterator for going over all elements of a collection. For a to a greater extent than in-depth discussion, run into here
Well, elbow grease it earlier you lot expression at the explanation after the code. It's genuinely this sort of nestling details nearly Java programming linguistic communication in addition to Collection framework, which volition brand you lot a skilful developer, in addition to besides assistance you lot to acquire your Java certification if you lot are preparing for it.
This code doesn't throw ConcurrentModificationException because hither nosotros are not using Iterator but nosotros are simply using traditional for loop.
It's the Iterator which throws ConcurrentModificationException, in addition to non the take away method of ArrayList, so you lot don't run into that mistake inwards below code.
If you lot expression at the code for ArrayList.java, you lot volition notice that in that location is a nested shape which implemented Iterator interface in addition to it's next() method calls checkForComodification() portion which genuinely checks if ArrayList has modified during iteration or not, if modCount doesn't check amongst expectedModCount in addition to so it throws ConcurrentModificationException.
This sort of questions are besides real pop on Oracle Java Certification e.g. OCAJP (1z0-808) in addition to OCPJP (1Z0-809), so if you lot are preparing for those exams, you lot should know the answer.
Here is the amount code snippet from the ArrayList.java shape for your quick reference:
The existent work amongst this code is that fifty-fifty though the code is using Iterator to acquire over ArrayList, it's non genuinely using the Iterator.remove() method to take away the element. It is simply using Iterator to acquire the adjacent chemical component but calling the ArrayList.remove() method to delete the element.
I know, it looks slowly when you lot know the argue but inwards existent time, many times programmer guide maintain fifty-fifty hours to figure out what is wrong. So, simply beware of that.
Btw, if you lot are learning Java in addition to so I propose joining Complete Java Masterclass to larn Java amend in addition to avoid such mutual errors.
The same demeanor is applicable to ListIterator every bit well. I hateful you lot tin post away supercede Iterator amongst ListIterator in addition to code volition move fine. The ListIterator besides allow you lot to navigate inwards both directions i.e. forwards in addition to backward.
That's all nearly how to avoid ConcurrentModificationException piece removing elements from ArrayList during iteration. You tin post away purpose the same technique to avoid ConcurrentModificationException piece removing elements from whatever other collection classes which guide maintain fail-fast Iterator e.g. LinkedList. Btw, if you lot are novel to Java programming in addition to so joining a good, comprehensive course of written report like Java Basics: Learn to Code the Right Way on Udemy tin post away assistance you lot to larn Java amend in addition to quicker.
Other Java troubleshooting Guides you lot may like
How to solve ArrayIndexOutOfBoundsException inwards Java? (guide)
How to solve NullPointerException inwards Java? (guide)
How to solve the "System cannot discovery the Path specified" error? (solution)
How to solve NoClassDefFoundError piece running Java computer program from a ascendence line? (solution)
How to solve "No JVM found, Please install 64-bit JDK" mistake inwards Android Studio? (solution)
How to bargain amongst SQLException "No Suitable driver constitute " mistake inwards JDBC in addition to MySQL? (guide)
How to solve NumberFormatException inwards Java? (guide)
How to solve Minecraft - java.lang.UnsatisfiedLinkError: lwjgl64.dll : Access Denied? (solution)
How to ready java.lang.ArrayIndexOutOfBoundsException: 1 inwards Java? (solution)
How to ready java.net.SocketException: Software caused connectedness abort: recv failed (fix)
Thanks for reading this tutorial, if you lot similar this tutorial in addition to so delight portion amongst your friends in addition to colleagues. If you lot guide maintain whatever inquiry or proposition in addition to so delight drib a comment.
The primary work amongst this mistake is that it confuses developer that listing is getting modified past times multiple threads in addition to that's why Java is throwing this error, it's non true. Most of the fourth dimension ConcurrentModificationException comes fifty-fifty without multiple threads modifying the list.
It's misnomer, don't acquire fooled away past times this. though it seems natural thinking that possibly approximately other thread is trying to alter the collection at the same time, it's normally breaking the Java rule.
In this article, I'll explicate this mistake in addition to we'll many code instance to reproduce this code fifty-fifty amongst the unmarried thread in addition to larn how nosotros tin post away avoid concurrent change mistake piece modifying an ArrayList inwards Java.
Btw, if you lot are non familiar amongst collection classes e.g. ArrayList itself in addition to so you lot should bring together an online course of written report e.g. Java Basics: Learn to Code the Right Way on Udemy is a skilful house to start with.
ConcurrentModificationException inwards Single Thread
This is the showtime instance of reproducing the concurrent change exception inwards Java. In this program, nosotros are iterating over ArrayList using the enhanced foreach loop in addition to removing selective elements e.g. an chemical component which matches sure enough status using ArrayList's remove method.For example, inwards the below code nosotros guide maintain showtime added a dyad of skilful programming books e.g. Programming Pearls, Clean Code, Effective Java, in addition to Code Complete into ArrayList in addition to and so removing whatever chemical component which has Code inwards its title.
package beginner; import java.util.ArrayList; import java.util.List; public class HelloWorldApp{ public static void main(String... args){ List<String> listOfBooks = new ArrayList<>(); listOfBooks.add("Programming Pearls"); listOfBooks.add("Clean Code"); listOfBooks.add("Effective Java"); listOfBooks.add("Code Complete"); // Using forEach loop to iterate in addition to removing // chemical component during iteration volition throw // ConcurrentModificationException inwards Java for(String book: listOfBooks){ if(book.contains("Code"));{ listOfBooks.remove(book); } } } } Output Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at beginner.HelloWorldApp.main(HelloWorldApp.java:18)
You tin post away run into that this mistake comes fifty-fifty though nosotros simply guide maintain i thread, primary thread which is operating amongst ArrayList. The ConcurrentModification mistake comes because nosotros are non using Iterator, instead simply calling listOfBooks.remove() method.
In this code, I guide maintain used Java 1.5 enhanced for loop, you lot must know how enhanced for loop industrial plant inwards Java.
Difference betwixt for loop in addition to enhanced for loop is that afterwards internally uses an Iterator for going over all elements of a collection. For a to a greater extent than in-depth discussion, run into here
Using Classical for loop in addition to ArrayList.remove(index)
Here is approximately other interesting code instance of removing elements from ArrayList. Surprisingly this code volition non throw ConcurrentModificationException when you lot showtime run it? make you lot know why?Well, elbow grease it earlier you lot expression at the explanation after the code. It's genuinely this sort of nestling details nearly Java programming linguistic communication in addition to Collection framework, which volition brand you lot a skilful developer, in addition to besides assistance you lot to acquire your Java certification if you lot are preparing for it.
package beginner; import java.util.ArrayList; import java.util.List; public class HelloWorldApp{ public static void main(String... args){ List<String> listOfBooks = new ArrayList<>(); listOfBooks.add("Programming Pearls"); listOfBooks.add("Clean Code"); listOfBooks.add("Effective Java"); listOfBooks.add("Code Complete"); System.out.println("List earlier : " + listOfBooks); for(int i=0; i<listOfBooks.size(); i++){ String mass = listOfBooks.get(i); if(book.contains("Programming")){ System.out.println("Removing " + book); listOfBooks.remove(i); // volition throw CME } } System.out.println("List after : " + listOfBooks); } } Output List earlier : [Programming Pearls, Clean Code, Effective Java, Code Complete] Removing Programming Pearls List after : [Clean Code, Effective Java, Code Complete]
This code doesn't throw ConcurrentModificationException because hither nosotros are not using Iterator but nosotros are simply using traditional for loop.
It's the Iterator which throws ConcurrentModificationException, in addition to non the take away method of ArrayList, so you lot don't run into that mistake inwards below code.
If you lot expression at the code for ArrayList.java, you lot volition notice that in that location is a nested shape which implemented Iterator interface in addition to it's next() method calls checkForComodification() portion which genuinely checks if ArrayList has modified during iteration or not, if modCount doesn't check amongst expectedModCount in addition to so it throws ConcurrentModificationException.
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
This sort of questions are besides real pop on Oracle Java Certification e.g. OCAJP (1z0-808) in addition to OCPJP (1Z0-809), so if you lot are preparing for those exams, you lot should know the answer.
Here is the amount code snippet from the ArrayList.java shape for your quick reference:
Using Iterator but ArrayList's take away method
Now, let's run into approximately other code example, where Java programmer thinks he has done everything correct but nevertheless getting the concurrent change exception. Can you lot location the error? It's genuinely mutual in addition to I guide maintain seen this sort of code a lot of fourth dimension on Java forums, StackOverflow in addition to on Facebook Java groups where they asked to ready the problem.package beginner; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class HelloWorldApp{ public static void main(String... args){ List<String> listOfBooks = new ArrayList<>(); listOfBooks.add("Programming Pearls"); listOfBooks.add("Clean Code"); listOfBooks.add("Effective Java"); listOfBooks.add("Code Complete"); Iterator<String> iterator = listOfBooks.iterator(); while(iterator.hasNext()){ String mass = iterator.next(); listOfBooks.remove(book); } } } Output Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at beginner.HelloWorldApp.main(HelloWorldApp.java:18)
The existent work amongst this code is that fifty-fifty though the code is using Iterator to acquire over ArrayList, it's non genuinely using the Iterator.remove() method to take away the element. It is simply using Iterator to acquire the adjacent chemical component but calling the ArrayList.remove() method to delete the element.
I know, it looks slowly when you lot know the argue but inwards existent time, many times programmer guide maintain fifty-fifty hours to figure out what is wrong. So, simply beware of that.
Btw, if you lot are learning Java in addition to so I propose joining Complete Java Masterclass to larn Java amend in addition to avoid such mutual errors.
Right agency to take away chemical component is past times using Iterator's take away method
Finally, hither is the correct agency to delete an chemical component from ArrayList during iteration. In this example, nosotros guide maintain used Iterator both iterate every bit good every bit take away the element. The code is ok but it has a serious limitation, you lot tin post away alone purpose this code to take away the electrical current element. You cannot take away whatever arbitrary chemical component from ArrayList inwards Java.package beginner; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class HelloWorldApp{ public static void main(String... args){ List<String> listOfBooks = new ArrayList<>(); listOfBooks.add("Programming Pearls"); listOfBooks.add("Clean Code"); listOfBooks.add("Effective Java"); listOfBooks.add("Code Complete"); System.out.println("List earlier : " + listOfBooks); Iterator<String> iterator = listOfBooks.iterator(); while(iterator.hasNext()){ String mass = iterator.next(); System.out.println("Removing " + book); iterator.remove(); } System.out.println("List after : " + listOfBooks); } } Output List earlier : [Programming Pearls, Clean Code, Effective Java, Code Complete] Removing Programming Pearls Removing Clean Code Removing Effective Java Removing Code Complete List after : []
The same demeanor is applicable to ListIterator every bit well. I hateful you lot tin post away supercede Iterator amongst ListIterator in addition to code volition move fine. The ListIterator besides allow you lot to navigate inwards both directions i.e. forwards in addition to backward.
That's all nearly how to avoid ConcurrentModificationException piece removing elements from ArrayList during iteration. You tin post away purpose the same technique to avoid ConcurrentModificationException piece removing elements from whatever other collection classes which guide maintain fail-fast Iterator e.g. LinkedList. Btw, if you lot are novel to Java programming in addition to so joining a good, comprehensive course of written report like Java Basics: Learn to Code the Right Way on Udemy tin post away assistance you lot to larn Java amend in addition to quicker.
Other Java troubleshooting Guides you lot may like
How to solve ArrayIndexOutOfBoundsException inwards Java? (guide)
How to solve NullPointerException inwards Java? (guide)
How to solve the "System cannot discovery the Path specified" error? (solution)
How to solve NoClassDefFoundError piece running Java computer program from a ascendence line? (solution)
How to solve "No JVM found, Please install 64-bit JDK" mistake inwards Android Studio? (solution)
How to bargain amongst SQLException "No Suitable driver constitute " mistake inwards JDBC in addition to MySQL? (guide)
How to solve NumberFormatException inwards Java? (guide)
How to solve Minecraft - java.lang.UnsatisfiedLinkError: lwjgl64.dll : Access Denied? (solution)
How to ready java.lang.ArrayIndexOutOfBoundsException: 1 inwards Java? (solution)
How to ready java.net.SocketException: Software caused connectedness abort: recv failed (fix)
Thanks for reading this tutorial, if you lot similar this tutorial in addition to so delight portion amongst your friends in addition to colleagues. If you lot guide maintain whatever inquiry or proposition in addition to so delight drib a comment.