HashMap在遍历的过程中修改(remove操作)

1.如下的方式删除键值对不会抛出异常

 1 Iterator modifyIter = finalResult.entrySet().iterator();
 2         while(modifyIter.hasNext()){
 3             Map.Entry modifyEntry = (Map.Entry)modifyIter.next();
 4             int keyOut =(int) modifyEntry.getKey();
 5             HashMap<Integer,ArrayList<Mac>> value = (HashMap<Integer,ArrayList<Mac>>) modifyEntry.getValue();
 6             Iterator innerIter = value.entrySet().iterator();
 7             while(innerIter.hasNext()){
 8                 Map.Entry innerEntry = (Map.Entry) innerIter.next();
 9                 int keyIn = (int) innerEntry.getKey();
10                 ArrayList<Mac> macList = (ArrayList<Mac>) innerEntry.getValue();
11                 if(macList.size()<groupSize){
12                     innerIter.remove();
13                     
14                 }
15             }
16             if(finalResult.get(keyOut).isEmpty()){
17                 modifyIter.remove();
18             }
19         }

2.否则直接通过finalResult.remove(key)修改hashmap时会在remove()执行之后抛出异常

posted @ 2016-08-24 17:18  destinying  阅读(3040)  评论(0编辑  收藏  举报