foreach remove 时出现并发修改异常

例如:


List overlays = mapView.getOverlays();
// for (Overlay overlay : overlays) {
// if (overlay instanceof MyLocationOverlay
// | overlay instanceof MyPoiOverlay) {
// } else {
// overlays.remove(overlay);
// }
// }   直接remove并发异常



可改为:


List overlays = mapView.getOverlays();
Overlay overlayToDel = null;
for (Overlay overlay : overlays) {
if (overlay instanceof MyLocationOverlay | overlay instanceof MyPoiOverlay) {

} else {
overlayToDel = overlay;
}
}
overlays.remove(overlayToDel);

或:

使用CopyOnWriteArrayList, CopyOnWriteArraySet实现,

  1. List list = new CopyOnWriteArrayList();  
  2. list.add("Alpha");  
  3. list.add("Beta");  
  4. list.add("Cat");  
  5. list.add("Dog");          
  6. for (String s : list) {  
  7.     if (!"".equals(s)) {                      
  8.         list.remove(s);  
  9.     }  

你可能感兴趣的:(foreach remove 时出现并发修改异常)