1.异常java一边遍历一边删除集合中的元素会报异常ConcurrentModificationException
2.正确的做法如下:
package list;
import java.util.*;
public class Demo {
public static void main(String[] args) {
List obj = new ArrayList();
obj.add("a");
obj.add("b");
obj.add("c");
System.out.println("移除前:" + obj.toString());
Iterator it = obj.iterator();
for(int i=0; i
System.out.println(i);
Object name = it.next();
if("a".equals(name) || "b".equals(name)){
it.remove();
i--;
}
}
System.out.println("移除后: " + obj.toString());
}
}
package set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Set obj = new HashSet();
obj.add("a");
obj.add("b");
obj.add("c");
System.out.println("移除前:" + obj.toString());
Iterator it = obj.iterator();
for(int i=0; i
System.out.println(i);
Object name = it.next();
if("a".equals(name) || "b".equals(name)){
it.remove();
i--;
}
}
System.out.println("移除后: " + obj.toString());
}
}
//遍历map的方法:
Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}