Set frame-iterator concurrency modification exception concurrentmodificationexception

Source: Internet
Author: User

Problem:
I have a collection, such as the next, I would like to determine if there is no "world" this element, if any, I will add a "Java ee" element, please write code implementation.

exceptions that occur with ordinary iterators:
Concurrentmodificationexception: This exception is thrown when the method detects concurrent modifications to an object, but does not allow this modification.

causes of the production:
Iterators are dependent on the collection and exist, after the success of the judgment, the collection of new elements added, and the iterator does not know, so the error, this error is called concurrency modification exception.
In fact, this problem describes: when an ordinary iterator iterates through an element, the element cannot be modified by a collection.

Solution:
A: Iterator iteration element, iterator modification element
The element is followed by the element that was just iterated.
B: Set traversal element, set modify element (normal for loop traversal)
The element is added at the end.

1 Importjava.util.ArrayList;2 ImportJava.util.Iterator;3 Importjava.util.List;4 ImportJava.util.ListIterator;5 6  Public classListIteratorDemo2 {7      Public Static voidMain (string[] args) {8         //To Create a list collection Object9List List =NewArrayList ();Ten         //adding elements OneList.add ("Hello"); AList.add ("World"); -List.add ("Java"); -  the         //Normal iterator Traversal -         //Iterator it = List.iterator (); -         //While (It.hasnext ()) { -         //string s = (string) it.next (); +         //if ("World". Equals (s)) { -         //list.add ("Java ee");//error here!!!  +         // } A         // } at  - Method 1: Iterator iteration element, iterator modification element - The iterator iterator does not add functionality, so we use its sub-interface Listiterator -Listiterator lit =list.listiterator (); -          while(Lit.hasnext ()) { -String s =(String) Lit.next (); in             if("World". Equals (s)) { -Lit.add ("Java ee"); to             } +         } -  the Method 2: Set traversal element, set modify element (normal for) *          for(intx = 0; x < List.size (); X + +) { $String s =(String) list.get (x);Panax Notoginseng             if("World". Equals (s)) { -List.add ("Java ee"); the             } +         } A  theSystem.out.println ("list:" +list); +     } -}

In addition, it is particularly noteworthy that the use of the Remove () method of this iterator removes the last element returned by the iterator from the collection pointed to by the iterator (optional action). This method can only be called once per call to next. If you modify the collection that the iterator points to by calling this method (remove method) in the iteration, the behavior of the iterator is indeterminate. When designing the Iterator<t> interface, the interface designer has pointed out that the call to the Remove () method in addition to the iterator to modify the collection that the iterator points to will cause an indeterminate effect when iterating. What happens depends on the specific implementation of the iterator. In the case of the possible consequences of this uncertainty, one of the ArrayList is encountered: An iterator throws a Concurrentmodificationexception exception. The specific exception situation is shown in the following code:

1 Importjava.util.ArrayList;2 Importjava.util.Collection;3 ImportJava.util.Iterator;4 5  Public classItaratortest {6 7      Public Static voidMain (string[] args) {8collection<string> list =NewArraylist<string>();9List.add ("Android");TenList.add ("IOS"); OneList.add ("Windows Mobile"); A  -Iterator<string> Iterator =list.iterator (); -          while(Iterator.hasnext ()) { theString lang =Iterator.next (); -List.remove (lang);//Would throw concurrentmodificationexception -         } -     } +  -}

This code throws a Concurrentmodificationexception exception at run time because we do not use the iterator remove () method to delete the element while the iterator is running, but instead uses the ArrayList remove () Method changes the collection that the iterator points to. This violates the design principle of the iterator, so an exception occurred.

Summarize:

    • When traversing collection with an iterator iterator, if you want to modify collection during traversal, you must do so by iterator/listiterator, or you may have an "indeterminate consequence."

Set frame-iterator concurrency modification exception concurrentmodificationexception

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.