Solution to Java. util. concurrentmodificationexception

Source: Internet
Author: User

 

For (INT I = 0; I <list. Size (); I ++) {// This method does not affect the addition or deletion of a set when traversing the set.

// List. Remove (list. Get (I ));

}

 

When performing iterative traversal on a map and deleting some key-value pairs that meet the conditions

Java. util. concurrentmodificationexception.
Exception in thread "Main" Java. util. concurrentmodificationexception
At java. util. hashmap $ hashiterator. nextentry (hashmap. Java: 787)
At java. util. hashmap $ keyiterator. Next (hashmap. Java: 823)

The solution is as follows:

Import java. util .*;

Public class testmap {
Public testmap (){
}

Public static void main (string [] ARGs ){
Java. util. Map M = new java. util. hashmap ();
M. Put ("AAA", "lizongbo ");
M. Put ("BBB", "lizongbo ");
M. Put ("CCC", "lizongbo ");
M. Put ("DDD", "lizongbo ");
M. Put ("eee", "lizongbo ");
M. Put ("fff", "lizongbo ");
M. Put ("ggg", "lizongbo ");
M. Put ("adads", "lizongbo ");
M. Put ("dffd", "lizongbo ");
M. Put ("dcxv", "lizongbo ");
M. Put ("lizongbo", "lizongbo ");
M. Put ("ERT", "lizongbo ");
M. Put ("544", "lizongbo ");
Iterator = M. keyset (). iterator ();
While (iterator. hasnext ()){
String sessionid = (string) iterator. Next ();
If ("ggg". Equals (sessionid) | "lizongbo". Equals (sessionid) |
& Quot; 544 & quot;. Equals (sessionid )){
Iterator. Remove (); // This line of code is critical.
M. Remove (sessionid );
}
}
System. Out. println (M. Get ("ggg "));
System. Out. println (M. Get ("lizongbo "));
System. Out. println (M. Get ("544 "));
}

 

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.