在阅读阿里巴巴规约的时候发现有一条规约是关于List的【不要在foreach里面进行元素的remove/add操作,remove请使用Iterator方式】。
原因
关键点就是因为每次list.size()都会重新计算长度才会导致问题出现 正确姿势:
for (Iterator
<Map
.Entry
<String, String>> it
= aMap
.entrySet().iterator(); it
.hasNext();){
Map
.Entry
<String, String> item
= it
.next();
if(item
.getValue()==null
) {
it
.remove();
}
}
jdk1.8之后可使用removeIf,这里根上面是一样效果
m1.entrySet().removeIf(item -> item.getValue() == null);
list同样有removeIf方法