Do not perform the remove/add operation of elements in the Foreach loop. remove element use Iterator mode, if concurrent operation, need to lock the Iterator object

Source: Internet
Author: User
Tags foreach

Do not perform the remove/add operation of elements in the Foreach loop. The remove element uses the Iterator method, which requires a lock on the Iterator object if the concurrency operation.

Positive example: iterator<string> Iterator = List.iterator ();

while (Iterator.hasnext ()) {

String item = Iterator.next ();

If (delete element's condition) {

Iterator.remove ();

}

}

Counter example: list<string> List = new arraylist<string> ();

List.add ("1");

List.add ("2");

for (String item:list) {

if ("1". Equals (item)) {

List.remove (item);

}

}

Note: The above code implementation results will certainly surprise everyone, then try to replace "1" with "2", will be the same result.


The root cause is that Expectedmodcount and modcount they are unequal, because of the execution of the ArrayList in the Remove (), modcount in each cycle value will change, and Expectedmodcount did not happen, An exception is thrown when the Checkforcomodification () method is executed.

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.