Concurrentmodificationexception issues with the "Java Fundamentals" list iteration and modification

Source: Internet
Author: User
Tags concurrentmodificationexception

Now there is a need to traverse a list, assuming that the list contains a string object, and then the need to judge if there is an object, then add a new object in. Naturally, we draw the following code:

Importjava.util.ArrayList;ImportJava.util.Iterator;Importjava.util.List;/*** Created by Lili on 15/11/13.*/ Public classTest { Public Static voidMain (string[] args) {List List=NewArrayList (); List.add ("Lucy"); List.add ("Polo"); List.add ("Shery"); //Exception in thread "main" Java.util.ConcurrentModificationExceptionIterator it =List.iterator ();  while(It.hasnext ()) {String str=(String) it.next (); if(Str.equals ("Polo") {List.add ("Pony"); }        }    }}

However, the code will error: concurrentmodificationexception, query this exception in the API, explained as follows:

 Public class concurrentmodificationexception extends RuntimeException This exception is thrown when the method detects concurrent modifications to an object, but does not allow this modification. For example, when a thread iterates on a Collection, it usually does not allow another linear modification of the Collection. Usually in these cases, the result of the iteration is indeterminate. If this behavior is detected, some iterator implementations (including all common collection implementations provided by the JRE) may choose to throw this exception. The iterator that performs the operation is called a fast-failed iterator, because the iterator quickly fails completely without risking any indeterminate behavior at any time in the future. Note that this exception does not always indicate that an object has been modified concurrently by a different thread. If a single thread emits a method call sequence that violates an object contract, the object may throw this exception. For example, an iterator throws this exception if the thread uses a fast-failed iterator to directly modify the collection when iterating over the collection. Note that the fast failure behavior of iterators is not guaranteed because, in general, it is not possible to make any hard guarantees as to whether or not there is a concurrency change in sync. A quick failure operation will do its best to throw concurrentmodificationexception. Therefore, it is a bad practice to write a program that relies on this exception to improve the correctness of such operations: Concurrentmodificationexception should only be used to detect bugs. Start from the following versions:1.2

From the description of this exception, this exception is not just for List, but for all collection containers (list,set), if there are changes in the iteration, it will appear.

So how can we solve this problem?

    1. Add the object using the iterator itself, but add it with Listiterator: The iterator has only the hashnext,next and remove methods, and Listiterator has the add and forward traversal methods.
    2. Use the For loop to iterate through the judgments and add them.
Importjava.util.ArrayList;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.ListIterator;/*** Created by Lili on 15/11/13.*/ Public classTest { Public Static voidMain (string[] args) {List List=NewArrayList (); List.add ("Lucy"); List.add ("Polo"); List.add ("Shery"); //Exception in thread "main" Java.util.ConcurrentModificationException//Iterator it = List.iterator ();//While (It.hasnext ()) {//string str = (string) it.next ();//if (str.equals ("Polo")) {//List.add ("Pony");//            }//        }Listiterator listit=List.listiterator ();  while(Listit.hasnext ()) {String str=(String) listit.next (); if(Str.equals ("Polo") {Listit.add ("Pony"); }            if(Str.equals ("Shery") {Listit.add ("Keity");        }} System.out.println (list);  for(inti = 0; I < list.size (); i++){            if(List.get (i). Equals ("Polo")) {List.add ("Pony"); }            if(List.get (i). Equals ("Shery") {List.add ("Keity");    }} System.out.println (list); }}

However, from the printing results, the two additions are still different, the first way is to add after the current traversal element, the second is appended on the last side.

0

Java Fundamentals List Iteration and concurrentmodificationexception problems that occur when you modify

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.