1 public static void main(String[] args) { 2 List<String> list = new ArrayList<String>(); 3 list.add("1"); 4 list.add("2"); 5 list.add("3"); 6 list.add("4"); 7 list.add("5"); 8 System.out.println("Original list : " + list); 9 System.out.println(); 10 11 for (String temp : list) { 12 System.out.println("Check for " + temp); 13 if ("3".equals(temp)) { 14 list.remove(temp); 15 } 16 } 17 18 System.out.println("Removed list : " + list); 19 }
执行以上代码抛出 java.util.ConcurrentModificationException 异常
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); System.out.println("Original list : " + list); System.out.println(); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()){ String temp = iterator.next(); System.out.println("Check for " + temp); if("3".equals(temp)){ iterator.remove(); } } System.out.println("Removed list : " + list); }
使用迭代器可以正常执行
标签:java,temp,List,list,System,util,add,println,out From: https://www.cnblogs.com/LazyLee024/p/16949827.html