For each循环中使用remove方法。
List<String> list =new ArrayList<String>(); list.add("boss"); list.add("good"); list.add("No"); list.add("Fine"); System.out.println(list);//[boss, good, No, Fine] Collections.sort(list); System.out.println(list);//[Fine, No, boss, good] list.add("我们"); list.add("你就是"); list.add("他很调"); list.add("明天见"); int i=0; while(true){ for (String dwonCountCmd : list) { if (i<30) { System.out.println(dwonCountCmd+i); i++; } else{ //在循环中把集合的一个元素移除了,如果此时不break的话,就会报错 list.remove(dwonCountCmd); System.out.println(list.toString()); break; } } }
会报这种错
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at Test2.main(Test2.java:47)