How to delete elements in a Java collection

Source: Internet
Author: User
Keywords Java delete such as under Chen
Tags code delete how to java list public string
Often we want to delete some elements in the collection.  Some might write that. 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 is run with the following exception: Exception in thread ' main ' java.util.ConcurrentModificationException at java.util.abstractlist$ Itr.checkforcomodification (abstractlist.java:449) because the list cannot delete its elements while it is in the loop. Then I did it, a very stupid way, the idea is this: Create a list of the elements to be deleted specifically, after the loop, with the List.removeall method to remove the elements.  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 also solve the problem, but the method is too cumbersome, in fact, there can be a simpler 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 you know about the basics of 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.

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.