Concurrentmodificationexception problems in Java

Source: Internet
Author: User

1  Public Static voidHashseterror () {2map<string, set<string>> tempMap1 =NewHashmap<string, set<string>>();3          for(inti = 0; I < 10; i++) {4Set<string> set =NewHashset<string>();5 Set.add (string.valueof (i));6Set.add (String.valueof (i*10));7 Tempmap1.put (string.valueof (i), set);8         }9 Tenmap<string, set<string>> tempMap2 =NewHashmap<string, set<string>>(); One  Aset<string> set = Tempmap1.get (String.valueof (5)); -Tempmap2.put ("T", set); -          the          for(String str:set) { -set<string> Tempset = tempmap2.get ("T"); -Tempset.add (str+ "12");  -         } +  -}

Execute error

Analysis Reason:

Although there are no noticeable modifications and additions to the set, it has actually increased.

TempMap2 gets set<string> [5,50] from TempMap1, which points to TEMPMAP2 's key value reference to the Set<string> collection.

Therefore TempMap1 's key= "5" and TempMap2 's key= "T" point to the same set<string> set

When 17 rows change Tempmap2, the set set changes TempMap1 key= "5" of the value reference is constant but the object value has changed.

Workaround:

Tempmap2.put ("T", New Hashset<string> (set));
Using the keyword new to re-open a memory space, 2 references point to a different location, one change, and the other is unaffected.

Concurrentmodificationexception problems with Java

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.