Java loop traversal deletes the elements in the set list

Source: Internet
Author: User

Remove some elements from list and set

How the error code is written:

New Hashset<string>(); Set.add ("aaaaaa"); Set.add ("bbbbbb"); Set.add ("CCCCCC"); Set.add ("dddddd"), Set.add ("eeeeee"), Set.add ("FFFFFF"), Set.add ("GGGGGG" );  for (String str:set) {    if ("dddddd". Equals (str)) {        set.remove (str);    }}

Operation Error:

Exception in thread "main" java.util.ConcurrentModificationException at    java.util.hashmap$ Hashiterator.nextentry (Hashmap.java:793) at    java.util.hashmap$keyiterator.next (Hashmap.java: 828) at    Test2. Test1.main (Test1.java:16)

You cannot add or delete data from a set when you are traversing it as above

The correct code to be spelled

Set<string> set =NewHashset<string>(); Set.add ("AAAAAA"); Set.add ("BBBBBB"); Set.add ("CCCCCC"); Set.add ("DDDDDD"); Set.add ("Eeeeee"); Set.add ("FFFFFF"); Set.add ("GGGGGG"); Iterator<String> it =set.iterator (); while(It.hasnext ()) {String str=It.next (); if("DDDDDD". Equals (str))    {It.remove (); }} for(String str:set) {System.out.println (str);}

Output:

Aaaaaaffffffeeeeeebbbbbbccccccgggggg

Java loop traversal deletes the elements in the set list

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.