Methods for looping through the deletion of elements in the list and set set in Java (recommended) _java

Source: Internet
Author: User
Tags set set

Today, when doing a project, you need to delete some elements in the list and set, then use the Edge traversal, edge Delete method, but reported the following exception:

Concurrentmodificationexception

In order not to forget later, use the rotten pen to record it as follows:

The writing of the error code, that is, to quote the above exception:

set<checkwork> set = This.getuserdao (). GETALL (QF). Get (0). Getactioncheckworks ();
for (Checkwork checkwork:set) {
  if (checkwork.getstate () ==1) {
    set.remove (checkwork);
  }
}

Note: Using the above notation will report the above Concurrenmodificationexception exception, because the collection can not be removed while traversing.

The correct wording is as follows:

1. Traverse Delete List

list<checkwork> list = This.getuserdao (). GetAll ();
iterator<checkwork> chk_it = List.iterator ();
while (Chk_it.hasnext ()) {
  Checkwork checkwork = Chk_it.next ();
  if (Checkwork.getplanstate () ==1) {
    chk_it.remove ();
  }
}

2. Traversal Delete Set

set<checkwork> set = This.getuserdao (). GetAll (). Get (0). Getactioncheckworks ();
		Iterator<checkwork> it = Set.iterator ();
		while (It.hasnext ()) {
			Checkwork checkwork = It.next ();
			if (Checkwork.getstate () ==1) {
				it.remove ();
			}
		}

The above in the Java loop to delete the list and set of sets of elements in the set of methods (recommended) is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.