java的ConcurrentModificationException问题

 1 public static void HashSetError() {
 2         Map<String, Set<String>> tempMap1 = new HashMap<String, Set<String>>();
 3         for (int i = 0; i < 10; i++) {
 4             Set<String> set = new HashSet<String>();
 5             set.add(String.valueOf(i));
 6             set.add(String.valueOf(i*10));
 7             tempMap1.put(String.valueOf(i), set);
 8         }
 9 
10         Map<String, Set<String>> tempMap2 = new HashMap<String, Set<String>>();
11 
12         Set<String> set = tempMap1.get(String.valueOf(5));
13         tempMap2.put("t", set);
14         
15         for(String str:set){
16             Set<String> tempSet = tempMap2.get("t");
17             tempSet.add(str+"12");            
18         }
19 
20     }

执行报错

分析原因:

虽然没有明显的修改和增加set,但是实际上已经增加。

tempMap2 从tempMap1中获取Set<String>   [5,50],此时是把tempMap2的key值引用指向了Set<String>集合。

故而 tempMap1 的key="5" 和tempMap2 的key="t" 指向了同一Set<String>集合

当17行改变tempmap2的时候,Set集合改变   tempMap1 key="5"的value引用不变 但对象值已改变。

解决方法:

tempMap2.put("t", new HashSet<String>(set));
用关键字new重新开辟一块内存空间,2个引用分别指向不同的位置,其中一个改变,另一个不受影响。

posted on 2017-02-20 23:43  小董斌  阅读(136)  评论(0编辑  收藏  举报

导航