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     }

执行报错spa

分析缘由:code

虽然没有明显的修改和增长set,可是实际上已经增长。对象

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

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

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

解决方法:class

tempMap2.put("t", new HashSet<String>(set));用关键字new从新开辟一块内存空间,2个引用分别指向不一样的位置,其中一个改变,另外一个不受影响。
相关文章
相关标签/搜索