Home  >  Q&A  >  body text

java - Why does removing the last element in foreach report an error?

public static void main(String[] args) {

        List<String> a = new ArrayList<String>();
            
        a.add("1");
        a.add("2");
        a.add("23");
        for (String temp : a) {
            if ("23".equals(temp)) {
                a.remove(temp);
            }
        }
        System.out.println(a);
    }

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at wan.ForEach.main(ForEach.java:22)

PHP中文网PHP中文网2736 days ago880

reply all(5)I'll reply

  • 大家讲道理

    大家讲道理2017-05-17 10:06:40

    foreach是通过迭代器来实现的,使用迭代器遍历元素时,容器不能试图改变容器的结构,如remove、add操作会抛出异常; 可以使用迭代器的removeMethod to delete elements.

    reply
    0
  • 迷茫

    迷茫2017-05-17 10:06:40

    http://tyrion.iteye.com/blog/...

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-17 10:06:40

    The person above made it very clear. Here I will tell you two simple solutions
    1. Iterator deletion
    2. Copy the list to traverse, and then operate the original list.
    Of course iterator deletion is recommended

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-17 10:06:40

    What is said upstairs is very official. To put it bluntly, the method of for(Object obj:list) cannot call the remove method of list to delete elements, otherwise an exception will be thrown because the Iterator needs to be determined. structure, so there are two ways to delete it. One is to copy a list and remove the elements in the old list by looping through the new list, and the other is to use for(int i; i<count; i++) Loop, so you can delete it through the cursor. Just be careful not to cross the bounds of the array subscript.

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-17 10:06:40

    When you are counting eggs, if someone secretly puts eggs in your basket or takes away eggs, it will cause you to count incorrectly. Unless you take away or take in the eggs yourself, you can remember the same principle. This is also true in the program.

    reply
    0
  • Cancelreply