ArrayList 遍历无法修改值

    1. public class CopyOnWriteArrayListTest {
    2. public static void main(String[] args) {
    3. ArrayList<String>list = new ArrayList<>();
    4. list.add("1");
    5. list.add("2");
    6. list.add("3");
    7. list.add("4");
    8. list.add("5");
    9. Iterator<String> iterator = list.iterator();
    10. while (iterator.hasNext()) {
    11. System.out.println("list is" + list);
    12. String next = iterator.next();
    13. System.out.println(next);
    14. if (next.equals("2")) {
    15. list.remove("5");
    16. }
    17. if (next.equals("3")) {
    18. list.add("3 found");
    19. }
    20. }
    21. }
    22. }

    执行结果异常

    1. list is[1, 2, 3, 4, 5]
    2. 1
    3. list is[1, 2, 3, 4, 5]
    4. 2
    5. list is[1, 2, 3, 4]
    6. Exception in thread "main" java.util.ConcurrentModificationException
    7. at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
    8. at java.util.ArrayList$Itr.next(ArrayList.java:861)
    9. at com.example.concurrent.collections.CopyOnWriteArrayListTest.main(CopyOnWriteArrayListTest.java:25)

    替换成CopyOnWriteArrayList

    1. public class CopyOnWriteArrayListTest {
    2. public static void main(String[] args) {
    3. //ArrayList<String>list = new ArrayList<>();
    4. CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList();
    5. list.add("1");
    6. list.add("2");
    7. list.add("3");
    8. list.add("4");
    9. list.add("5");
    10. Iterator<String> iterator = list.iterator();
    11. while (iterator.hasNext()) {
    12. System.out.println("list is" + list);
    13. String next = iterator.next();
    14. System.out.println(next);
    15. if (next.equals("2")) {
    16. list.remove("5");
    17. }
    18. if (next.equals("3")) {
    19. list.add("3 found");
    20. }
    21. }
    22. }
    23. }