Implementation Code for deleting elements in a JAVA set

Source: Internet
Author: User

We often need to delete some elements in the set. Some may be written in this way.

Copy codeThe Code is as follows: public void operate (List list ){
For (Iterator it = list. iterator (); it. hasNext ();){
String str = (String) it. next ();
If (str. equals ("chengang ")){
List. remove (str );
}
}
}

If this method is used, the following exception is reported:

Exception in thread "main" java. util. ConcurrentModificationException
At java. util. effecactlist $ Itr. checkForComodification (effecactlist. java: 449)

Because list elements cannot be deleted in a loop. Later, I did this. It was a very stupid method. The idea was like this: Create a List to store the elements to be deleted. After the loop, use List. the removeAll method deletes an element. The Code is as follows:

Copy codeThe 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 solve the problem, but the method is too cumbersome. In fact, there can be a simpler and more efficient method, that is, the Iterator. remove method is used, as shown below:

Copy codeThe Code is as follows: for (Iterator it = list. iterator (); it. hasNext ();){
String str = (String) it. next ();
If (str. equals ("chengang ")){
It. remove ();
}
}

Therefore, the more basic Java knowledge you know, the more concise the code will be written. On the contrary, if your code is particularly complex, there must be a problem with the method or design.

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.