举个例子就可以了
也是网上看到的
也算个知识点吧
import java.util.ArrayList; import java.util.Iterator; public class TestList { public static void main(String[] args) { test1(); test2(); test3(); } public static void test1() { ArrayList<String> list = new ArrayList<String>(); list.add("one"); list.add("two"); list.add("two"); list.add("two"); list.add("two"); for (int i = 0; i < list.size(); i++) { if (list.get(i).equals("two")) { list.remove(i); } } System.out.println("test1 : " + list); } public static void test2() { ArrayList<String> list = new ArrayList<String>(); list.add("one"); list.add("two"); list.add("two"); list.add("two"); list.add("two"); for (String s : list) { if (s.equals("two")) { list.remove(s); } } System.out.println("test2 : " + list); } public static void test3() { ArrayList<String> list = new ArrayList<String>(); list.add("one"); list.add("two"); list.add("two"); list.add("two"); list.add("two"); Iterator<String> iter = list.iterator(); while (iter.hasNext()) { String s = iter.next(); if (s.equals("two")) { iter.remove(); } } System.out.println("test3 : " + list); } }
test1 : [one, two, two]
第二个方法报错
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at TestList.test2(TestList.java:34)
at TestList.main(TestList.java:8)
第三个方法输出
test3 : [one]
可以看出第三种方法删除比较正确