How to delete elements in a Java collection

Source: Internet
Author: User

Often we want to delete some elements in the collection. Some may write like this.

public void operate (List list) {

for (Iterator it = List.iterator (); It.hasnext ();) {

String str = (string) it.next ();

if (Str.equals ("Chengang")) {

List.remove (str);

}

}

}

This writing will report the following exception as soon as it runs:

Exception in thread "main" java.util.ConcurrentModificationException

At Java.util.abstractlist$itr.checkforcomodification (abstractlist.java:449)

Because the list is not allowed to delete its elements when it is in the loop. Later I did, a very stupid way, the idea is that: Create a list to be deleted from the element, after the loop, using the List.removeall method to delete the element. The code is as follows:

public void operate (List list) {

List removelist= new ArrayList ();

for (Iterator it = List.iterator (); It.hasnext ();) {

String str = (string) it.next ();

if (Str.equals ("Chengang")) {

Removelist.add (str);

}

}

List.removeall (removelist);

}

This can really solve the problem, but the method is too cumbersome, in fact, there can be more simple and more efficient way, is to use the Iterator.remove method, as follows:

for (Iterator it = List.iterator (); It.hasnext ();) {

String str = (string) it.next ();

if (Str.equals ("Chengang")) {

It.remove ();

}

}

So, the more basic knowledge you have about Java, the more concise your code will be. Conversely, if your code is particularly complex, there must be a problem with the method or design.

How to delete elements in a Java collection

Related Article

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.