Java Concurrentmodificationexception Exception Detailed __java

Source: Internet
Author: User

When Java iterates through the list, it throws an concurrentmodificationexception exception if the element is removed.

The exception is that when we iterate over elements, we remove the elements from the list collection at the same time.

It's no problem when we write code like this.

  list<string> list = new arraylist<> ();

        * *
        /List.add ("AAA");
        String value = null;
        for (int i = 0; i < list.size (); i++) {
            value = List.get (i);
            List.remove (value);
        }


However, when we write in this way, there is a problem.

  
       /* Throw concurrentmodificationexception
        list.add ("AAA");
        String value = null;
        for (iterator<string> iterator = List.iterator (); Iterator.hasnext ();) {
            value = Iterator.next ();
            List.remove (value);
        }
        * * *
               throw concurrentmodificationexception
        list.add ("AAA");
        for (string string:list) {
            list.remove (string);
        }
        * * *
               throw concurrentmodificationexception
        list.add ("AAA");
        List.foreach (s-> {
            list.remove (s);
        });
         */
The following report Concurrentmodificationexception exception is written because of the use of iterators to write.


This exception is not reported when we use the ArrayList subscript to visit.



Of course, it's OK to use iterators if you must. Use the method provided by the iterator for the remove operation.

List.add ("AAA");
        String value = null;
        for (iterator<string> iterator = List.iterator (); Iterator.hasnext ();) {
            value = Iterator.next ();
            Iterator.remove (); Use the Remove method provided by the iterator
        }

The above method is used in a single thread, in the context of multithreading can be considered with copyonwritearraylist

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.