1.异常java一边遍历一边删除集合中的元素会报异常ConcurrentModificationException
2.正确的做法如下:
package list;
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Object> obj = new ArrayList<Object>();
obj.add("a");
obj.add("b");
obj.add("c");
System.out.println("移除前:" + obj.toString());
Iterator<Object> it = obj.iterator();
for(int i=0; i<obj.size(); 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<Object> obj = new HashSet<Object>();
obj.add("a");
obj.add("b");
obj.add("c");
System.out.println("移除前:" + obj.toString());
Iterator<Object> it = obj.iterator();
for(int i=0; i<obj.size(); 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<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
原文地址:http://www.cnblogs.com/-liuhuanchao/p/4149806.html(侵删)
结尾:java8的新streamApi更方便,然而项目中用的是java7-